/*
 *Function used only in design time of form designer
 *
 *1. Class name conventions
 *
 *   fmdraggable : draggable
 *   element-tag-* : available components in left panel with type
 *   fmddragging : available components in dragging state
 *   fmdelement_* : dropped form element with type
 *   fmddropped : dropped form element
 *   fmcontainer_tab : first level tab container
 *   fmcontainer_block : container element
 *   fmcontainer_block_titlebar : container title bar div
 *   fmcontainer_block_content : container content div
 *   ui-* : jQuery ui classes with default jQuery ui behaviours
 *   
 *2. ID conventions
 *   ui-id-* : unique id in this form
 *
 */

//===== Constants

//dhx skin, should be re-initialized in JSP
dhx_skin = "dhx_skyblue";

//dhx images path, should be re-initialized in JSP
//dhtmlx.image_path;

//global context


function Designer() {

var fmd = {};
//======== designer vars
fmdc = {};

//design theme name, not the theme in runtime
fmdc.theme = 'formoid-default-skyblue';

//is in advanced view
fmdc.advancedview = false;

//image path
//fmdc.imagepath;

//column limit
fmdc.collimit = {};
fmdc.collimit.table = 3;	//table block
fmdc.collimit.div12 = 6;	//div 12 block

//properties cell default width
fmdc.cell_prop_width = 360;

//tip p html string
fmdc.tipp = '<p class="fmdtipp">'+fmd_i18n_tdp+'</p>';

//td html string - table pattern
fmdc.tdcell = '<td class="fmdtd fmdselectable" onclick="designer.onselect(event,this)">'+fmdc.tipp+'</td>';
fmdc.tdcell0 = '<td class="fmdtd fmdselectable" onclick="designer.onselect(event,this)"></td>';
//tr html string - table pattern
fmdc.trrow = '<tr class="fmdtr">'+fmdc.tdcell+'</tr>';
fmdc.trrow0 = '<tr class="fmdtr"></tr>';

//td html string - div12 pattern
fmdc.tdcelldiv12 = '<div class="fmdtd fmdselectable" onclick="designer.onselect(event,this)" fmdcols="12">'+fmdc.tipp+'</div>';
fmdc.tdcell0div12 = '<div class="fmdtd fmdselectable" onclick="designer.onselect(event,this)" fmdcols="12"></div>';
//tr html string - div12 pattern
fmdc.trrowdiv12 = '<div class="fmdtr">'+fmdc.tdcelldiv12+'</div>';
fmdc.trrow0div12 = '<div class="fmdtr"></div>';

//====== set Variables
fmdf_resetVars();


//====== JQuery UI Variables

//draggable arguments
fmdc.draggable_args = {
		revert: true,
		cursor: "move", 
		distance : 10,
		cursorAt: { top: 30, left: 50 },
		zIndex: 1,
		helper: fmdf_helper
	};

//draggable without helper, used to move dropped elements
fmdc.draggable_args_nohelper = {
		revert: true,
		cursor: "move", 
		distance : 10,
		cursorAt: { top: 30, left: 50 },
		zIndex: 1
	};

//droppable arguments
fmdc.droppable_args = {
		accept: fmdf_isAccept,
		activeClass: "ui-state-hover",
		hoverClass: "ui-state-active",
		drop: fmdf_onDrop
	};


//====== Functions

//init var
function fmdf_initvar(fmdvar) {
	fmd = fmdvar;
}

//init
function fmdf_init(formid, versionid) {
	$.when(fmdf_init_async(formid, versionid)).done(function() {
		waitend();
	});
}

//init
function fmdf_init_async(formid, versionid) {
	
	var dtd = $.Deferred();//使本方法异步执行

	function init_async() {
		//image path
		fmdc.imagepath = fmd.imagepath;
		//canvas vars
		fmdc.theme = 'formoid-default-skyblue';

		//disable context menu
		document.oncontextmenu = function(){return false;};
		
		//onkeyup
		$(document).bind('keyup', function(e){
			e = window.event || e;
			//alert(e.keyCode);
			if (e.keyCode==116 || e.keyCode==8) {
				e.keyCode = 0;
				return false;
			} else if (e.keyCode==46) { //delete key
				if (!fmd.isEditor) return false;
				//if there is a dhx popup, do nothing
				var haswindow = false;
				if(!fm_dhxWins) fm_dhxWins = new dhtmlXWindows();
				fm_dhxWins.forEachWindow(function(){
					haswindow = true;
			    });
				if (haswindow) return false;
				
				//if in a textinput
				if (document.activeElement.type && document.activeElement.type.indexOf('text')>=0
						&& $(document.activeElement).parents('.fmdcanvaswrapper').length==0 ) {
					return;
				}
				
				if (!e.ctrlKey) {
					/*fmdf_removeselectedtab();
				} else {*/
					confirmWarning('', fmd_i18n_msg_delconfirm, fmd_i18n_b_ok, fmd_i18n_b_cancel, function(){
						fmdf_removeselected();
					});
				}
			} else if (27==e.keyCode) {//esc
				if (fm_dhxWins) {
					  fm_dhxWins.forEachWindow(function(w){
						  w.close();
					  });
				}
			}
			return true;
		});
		
		//ctrl+c
		$(document).bind('keydown', 'Ctrl+c', function (e) {
			if(e.ctrlKey && e.which==67) {
				fmdf_markCopy();
			}
		});
		//ctrl+v
		$(document).bind('keydown', 'Ctrl+v', function (e) {
			e.ctrlKey && e.which==86 && fmdf_doCopy();
		});

		//onkeydown
		$(document).bind('keydown', 'Ctrl+Alt+s', function (e) {
			e.ctrlKey && e.altKey && e.which==83 && fmdf_save();
			/* if(e){
	            //因此它支持W3C的stopPropagation()方法 
	            e.preventDefault && e.preventDefault();
	            e.stopPropagation && e.stopPropagation();
	            e.returnvalue = false;
	        }else{
	            //否则我们使用ie的方法来取消事件冒泡
	            window.event.cancelBubble = true;
	        }
			e.keyCode = 0;
			return false; */
		});
		
		if (!formid || !versionid) {//new form
			fmdf_resetVars();
		}
		
		//init layout
		fmdf_initLayout();

		//jQuery ui init tab function
		fmdf_initTabs();

		//data
		if (formid && versionid) {
			fmdc.form_basic.disableItem("fi_basic_name");
			fmdc.form_basic.disableItem("fi_basic_desc");
			doPostAsyncJson(fmd.fmdCtx + "/rest/fmd/getVersion",
					{"formid" : formid, "versionid" : versionid},
					function(ret) {
						if (ret) {
							fmdc.form = ret.form;
							fmdc.version = ret.version;
							fmdf_wait(1);
							$.when(fmdf_loadSavedData()).done(function(){
								fmdf_wait(0);
							});
						}
					}, 
					function() {
						msgErr(fmd_i18n_msg_readfail);
						fmdf_wait(0);
					});
		} else {
			fmdf_wait(0);
		}
		
		dtd.resolve();
	}
	
	setTimeout(init_async(), 1);//make it async
	return dtd.promise();
}

//reset form designer vars
function fmdf_resetVars() {
	
	fmdc.form = {};
	fmdc.form.formtype = fmd.inputformtype;
	fmdc.version = {};
	//form designer data
	fmdc.version.formdata = {};
	//fmdc.version.formdata.tableNames = "TEST01,TEST02";
	//form designer properties config data
	fmdc.version.formdata.propconf = {};

	//default font size in px, the same as that in body css
	fmdc.fontsize = 16;
	//default canvas width in em, the same as width in class fmdcanvas
	fmdc.canvas_size_widthem  = 60;
	//auto hide elements prop
	fmdc.autohideprop = true;
	//properties cell
	//fmdc.cell_prop = null;
	//tab ui object
	fmdf_initTabs();
	//canvas status bar
	//fmdc.statusbar = null;
	//selection holder
	fmdc.selection = {selectedobj:null};
	fmdf_unselect();
	//tab page index for adding tab id
	fmdc.tabpageidx = 1;
	//fmcontainer index for adding container id
	fmdc.contidx = 1;
	//control index for adding new control
	fmdc.uiidx = 1;
	//models 
	fmdc.models = {};
	//tempdata for properties window of the designer
	fmdc.proptemp = null;
	//unsaved change flag
	fmdc.unsavedchange = false;
}

//reset form designer canvas
function fmdf_cleanCanvas() {
	fmdf_unselect();
	$('.fmdcanvas').children("ul").empty();
	$('.fmdcanvas').children("div").remove();
}

//reset ui behaviours
/*function fmdf_resetUiBehaviour() {
	fmdf_setsortable();
	fmdf_initTabs();
	fmdc.tabs.tabs( "refresh" ).tabs({ active: 0 });
	$('.fmcontainer_block td').droppable(fmdc.droppable_args);
	$('.fmddropped').draggable(fmdc.draggable_args_nohelper);
}*/

//helper function on dragging start
function fmdf_helper(event) {
	//check type
	var classes = event.target.className.split(' ');
	var type = null;
	for (var i in classes) {
		if (classes[i].indexOf('element-tag-')!=-1) {	//class start with element-tag- is draggable(available elements)
			type = classes[i].substr(12);
			break;
		} else if (classes[i].indexOf('fmdelement_')!=-1) {	//class start with fmdelement is draggable(dropped elements)
			type = classes[i].substr(11);
			break;
		}
	}
	//console.debug("dragging type:"+type);
	if (fmdmeta_prop.control[type] && fmdmeta_prop.control[type].innerhtml_dragging) {
		return $( '<div class="fmddragging fmdelement_'+type+'" >'+
				eval("fmdmeta_prop.control[type].innerhtml_dragging" + (typeof(fmdmeta_prop.control[type].innerhtml_dragging)=="function" ? "()":""))+
				'</div>' );
	}
	return $( '<div class="fmddragging fmdelement_none" >'+fmd_i18n_notavailable+'</div>' );
}

//on drop event handler
function fmdf_onDrop( event, ui ) {
	//$( this ).addClass( "ui-state-highlight" );
	if (ui.draggable.parent().attr("id")==$(this).attr("id")) {
		//console.debug("fmdf_onDrop element moved but moved to original cell. donothing...");
		return;
	}

	//get type
	var classes = ui.draggable.attr('class').split(' ');
	//console.debug('fmdf_onDrop existing classes='+classes);
	var type = null;
	if (fmdf_hasClass(ui.draggable, 'fmddropped')) {	// move existing element
		for (var i in classes) {
			if (classes[i].indexOf('fmdelement_')!=-1) {	//class start with fmdelement is acceptable(dropped elements)
				type = classes[i].substr(11);
				break;
			}
		}
	} else {
		for (var i in classes) {
			if (classes[i].indexOf('element-tag-')!=-1) {	//class start with element-tag- is acceptable(available elements)
				type = classes[i].substr(12);
				break;
			}
		}
	}

	//check existing
	//console.debug("$(this).find('.fmddropped').length="+$(this).find('.fmddropped').length);
	var existingElem = $(this).find('.fmddropped');
	var hasExisting = existingElem.length>0;
	var multielement = !!fmdmeta_prop.control[type].multielement;
	//only same type can in one
	if (hasExisting && (!multielement || !existingElem.hasClass('fmdelement_'+type)) ){
		dhtmlx.message(fmd_i18n_msg_delexistingfirst);
		return;
	}

	var oldid = null;
	if (fmdf_hasClass(ui.draggable, 'fmddropped')) {	// move existing element
		oldid = ui.draggable.attr('id');
		//console.debug("ui.draggable.html()=="+ui.draggable.html());
		var movingInnerHtml = ui.draggable.html();
		//console.debug('fmdf_onDrop existing ui id='+oldid);
		//set orginal td html code
		ui.draggable.parent().find('.fmddropped').length==1 && ui.draggable.parent().append(fmdc.tipp);//donot set tip <p> if element number > 1
		//remove existing element
		//console.debug('fmdf_onDrop removing existing ui:'+ui.draggable.html());
		ui.draggable.remove();
		var newhtml = '<div class="fmddropped fmdelement_'+type+'"' +
			(multielement ? ' style="float:left;margin:0.6em 0.4em 0.6em 0.4em;"' : '') +
			' onclick="designer.onselect(event,this);">'+movingInnerHtml+'</div>';
		if (hasExisting && multielement) {
			$(this).append(newhtml);
		} else {
			$(this).html(newhtml);
		}
		
	} else {	//creating new element
		//console.debug("fmdf_onDrop accepting type:"+type);
		if (fmdmeta_prop.control[type] && fmdmeta_prop.control[type].innerhtml_dropped){
			var newhtml = '<div class="fmddropped fmdelement_'+type+'" ' +
					(multielement ? ' style="float:left;margin:0.6em 0.4em 0.6em 0.4em;"' : '') +
					' onclick="designer.onselect(event,this);">'+
					eval("fmdmeta_prop.control[type].innerhtml_dropped" + (typeof(fmdmeta_prop.control[type].innerhtml_dropped)=="function" ? "()":""))+
					'</div>';
			if (hasExisting && multielement) {
				$(this).append(newhtml);
			} else {
				$(this).html(newhtml);
			}
		}
	}

	//set id
	var dropped = $(this).find('.fmddropped:last');
	if (oldid) {
		dropped.attr("id", oldid);
	} else {
		dropped.attr("id", fmdf_uiid());
	}
	//set draggable
	fmd.isEditor && dropped.draggable(fmdc.draggable_args_nohelper);
	
	//reset cells height for div12 block
	var fmdpattern = $(this).parents('.fmcontainer_block').attr("fmdpattern");
	if ('div12'==fmdpattern) {
		if($(this).children('.fmddropped').length>0) {
			$(this).height($(this).children().eq(0).height());
		}
		fmdf_refreshCellHeightDiv12($(this).parents('.fmdtr'));
	}
	
	//select the new component
	fmdf_select(dropped);
}

//on fmcontainer_block title bar clicked and select fmcontainer
function fmdf_fmcontainer_block_tbclick(event, thisdiv) {
	//fmdf_select($(thisdiv).parent());
	fmdf_onselect(event, $(thisdiv).parent());
}

//change current selected container title
function fmdf_fmcontainer_block_title(label) {
	var c = fmdc.selection.selectedobj;
	c.find('.fmcontainer_block_titlebar a').html('<b>'+label+'</b>');
}

//change current selected container header display
function fmdf_fmcontainer_block_headerdisplay(hide) {
	var c = fmdc.selection.selectedobj;
	//alert(hide);
	if (hide=='1'){
		c.find('.fmcontainer_block_titlebar').height('.1em');
		c.find('.fmcontainer_block_titlebar img').hide();
		c.find('.fmcontainer_block_titlebar a').hide();
	} else {
		c.find('.fmcontainer_block_titlebar').height('2em');
		c.find('.fmcontainer_block_titlebar img').show();
		c.find('.fmcontainer_block_titlebar a').show();
	}
}

//accept
function fmdf_isAccept($obj) {
	if ($($obj).attr('class')!=undefined) {
		var classes = $($obj).attr('class').split(' ');
		for (var i in classes) {
			if (classes[i]=='fmdraggable' || classes[i]=='fmddropped') {
				return true;
			}
		}
	}
	return false;
}

//on dom object clicked and select dom object
function fmdf_onselect(event, obj) {
	if (fmdc.selection.selectedobj && fmdc.selection.selectedobj.attr('id')==$(obj).attr('id')){
		//console.debug("selection not changed.");
		return;
	}
	fmdf_select($(obj));
	if(navigator.appName == 'Microsoft Internet Explorer') {
		event.cancelBubble=true; //ie s
	} else {
		event.stopPropagation(); //ff s
	}
}

//init tabs
function fmdf_initTabs() {
	
	//sortable tabs
	//$(".fmdcanvas").children("ul:first").find("li").removeClass("ui-state-default ui-corner-top ui-tabs-active ui-state-active fmdselected");
	//$(".fmdcanvas").children("div").removeClass("ui-tabs-panel ui-widget-content ui-corner-bottom");
	fmdc.tabs = $( ".fmdcanvas" ).tabs();
	if (fmd.isEditor) {
		fmdc.tabs.find( ".ui-tabs-nav" ).sortable({
			axis: "x",
			stop: function() {
				fmdc.tabs.tabs( "refresh" );
			}
		});
	}
}

//set sortable
function fmdf_setsortable() {
	//sortable
	if (fmd.isEditor) {
		$( ".fmform" ).sortable({
			placeholder: "ui-state-highlight"
		});
	}
	$( ".fmform" ).disableSelection();
}

//Append a tab
function fmdf_addtab(title, type, id) {
	var tabpageidx = null;
	if (id) {
		tabpageidx = id.substr(16);
	} else {
		if (fmdc.form.formtype=='PROCESS' && $('.fmdcanvas .fmdcanvas_tabnavli').length>0) {
			msg(fmd_i18n_msg_formonetabonly);
			return;
		}
		tabpageidx = fmdc.tabpageidx;
		fmdc.tabpageidx ++;
	}
	$('.fmdcanvas .fmdcanvas_tabnav').append('<li id="fmcontainer_tab_'+tabpageidx+'" class="fmdcanvas_tabnavli fmdselectable"><a href="#fmcontainer_tabbody_'+tabpageidx+'">'+title+'</a></li>');
	if (type=='business') {
		$('.fmdcanvas').append('<div class="fmcontainer_tab fmbusinesstab" id="fmcontainer_tabbody_'+tabpageidx+'"><form class="fmform"></form></div>');
		fmdf_setsortable();
	} else {
		$('.fmdcanvas').append('<div class="fmcontainer_tab fmsystemtab" id="fmcontainer_tabbody_'+tabpageidx+'"><div><p>'+fmd_i18n_t_systemtab+'</p></div></div>');
	}
	$('.fmdcanvas .fmdcanvas_tabnav .fmdcanvas_tabnavli:last').attr("tabtype", type).click(function(e){
		fmdf_select($(this));
		fmdf_stopEvent(e.originalEvent);
	});
	var tabsno = $('.fmdcanvas .fmdcanvas_tabnav').children().length - 1;
	//console.debug('current tab number is '+tabsno);
	fmdc.tabs.tabs( "refresh" ).tabs({ active: tabsno });
	fmdf_select($('#fmcontainer_tab_'+tabpageidx));
	fmdpf_apply();
}

//change tab title
function fmdf_fmcontainer_tab_title(label) {
	var t = fmdc.selection.selectedobj;
	t.find('a').html(label);
}

//Append a container
function fmdf_fmcontainer_block_addcontainer(fmdpattern, id) {
	var activetab = fmdc.tabs.find(".ui-tabs-active");
	if (activetab) {
		var tabcontent = $('#'+activetab.attr('aria-controls'));
		if(fmdf_hasClass(tabcontent, 'fmbusinesstab')) {
			var tbody1 = null;
			if ('table'==fmdpattern) {
				tbody1 = '<table class="fmcontainer_block_content">'+
						 	(id ? "" : fmdc.trrow) +
						 '</table>';
			} else if ('div12'==fmdpattern) {
				tbody1 = '<div class="fmcontainer_block_content">'+
							(id ? "" : fmdc.trrowdiv12) +
						 '</div>';
			}
			var id1 = id || "fmcontainer_block_"+ fmdc.contidx++;
			//append container
			var str1 = '<div id="'+ id1 +'" class="fmcontainer_block fmdselectable" fmdpattern="'+fmdpattern+'">'+
							'<div class="fmcontainer_block_titlebar">'+
							'<img align="absmiddle" src="'+fmdc.imagepath+'/collapse.png"/>'+
							'<a href="" onclick="return false;"><b>'+fmd_i18n_container_title+'</b></a>'+
							'</div>'+
							tbody1+
						'</div>';
			tabcontent.find('.fmform').append(str1);
			var block = tabcontent.find( ".fmcontainer_block:last" );
			if (!id) {
				block.hide().show("slide", {}, 300, null );
				block.find('.fmdtd').droppable(fmdc.droppable_args).attr("id", fmdf_uiid());
				if ('div12'==fmdpattern) {
					fmdf_refreshTdWidth(block.find(".fmdtr:last"), fmdpattern);
				}
			}
			block.find('.fmcontainer_block_titlebar').click(function(e){
				fmdf_fmcontainer_block_tbclick(e.originalEvent, this);
			}).find('img').click(function(e) {
				fmf_fmcontainer_block_togglecontent(this);
			});
			fmdf_select(block);
			return block;
		}
	}
}

//check if current tab is a business tab
/*function fmdf_isOnBiztab() {
	//get active tab in business type
	var activetab = fmdc.tabs.find(".ui-tabs-active");
	if (activetab) {
		//console.debug('active tab control====='+activetab.attr('aria-controls'));
		//console.debug('active tab control class====='+$('#'+activetab.attr('aria-controls')).attr('class'));
		if (fmdf_hasClass($('#'+activetab.attr('aria-controls')), 'fmbusinesstab')) {
			return true;
		}
	}
	return false;
}*/

//Append row to container
function fmdf_fmcontainer_block_appendtr() {
	if (!fmdc.selection.selectedobj) {
		return;
	}
	var $table = null;
	if ( fmdf_hasClass(fmdc.selection.selectedobj, 'fmcontainer_block') ) {
		$table = $(fmdc.selection.selectedobj).find('.fmcontainer_block_content');
	} else if ( fmdf_hasClass(fmdc.selection.selectedobj, 'ui-droppable') || fmdf_hasClass(fmdc.selection.selectedobj, 'fmddropped') ) {
		$table = $(fmdc.selection.selectedobj).parents('.fmcontainer_block_content');
	}
	//console.debug('$table='+$table);
	if (fmdf_hasClass($table, 'fmcontainer_block_content')) {
		//console.debug('$table class='+$table.attr('class'));
		var pattern = $table.parents('.fmcontainer_block').attr("fmdpattern");
		if ('table'==pattern) {
			$table.append(fmdc.trrow0);
		} else if ('div12'==pattern) {
			$table.append(fmdc.trrow0div12);
		}
		return $table.find(".fmdtr:last");
	}
	return null;
}

//Append row to container
function fmdf_fmcontainer_block_appendrow(id) {
	if (!fmdc.selection.selectedobj) {
		return;
	}
	var $table = null;
	if ( fmdf_hasClass(fmdc.selection.selectedobj, 'fmcontainer_block') ) {
		$table = $(fmdc.selection.selectedobj).find('.fmcontainer_block_content');
	} else if ( fmdf_hasClass(fmdc.selection.selectedobj, 'ui-droppable') || fmdf_hasClass(fmdc.selection.selectedobj, 'fmddropped') ) {
		$table = $(fmdc.selection.selectedobj).parents('.fmcontainer_block_content');
	}
	//console.debug('$table='+$table);
	if (fmdf_hasClass($table, 'fmcontainer_block_content')) {
		//console.debug('$table class='+$table.attr('class'));
		var pattern = $table.parents('.fmcontainer_block').attr("fmdpattern");
		if ('table'==pattern) {
			$table.append(fmdc.trrow);
		} else if ('div12'==pattern) {
			$table.append(fmdc.trrowdiv12);
			fmdf_refreshTdWidth($table.find(".fmdtr:last"), pattern);
		}
		////$table.find("tr:last").after(fmdc.trrow);
		////if($table.find('tr').length==0) {
			//$table.append(fmdc.trrow);
		////}
		var cell = $table.find(".fmdtr:last .fmdtd").droppable(fmdc.droppable_args);
		id ? cell.attr("id", id) : cell.attr("id", fmdf_uiid());
		return cell;
	}
	return null;
}

//add row before selected
function fmdf_fmcontainer_block_addrowbefore() {
	var $tr = fmdf_getselectedTR();
	if ($tr) {
		var pattern = $tr.parents('.fmcontainer_block').attr("fmdpattern");
		if ('table'==pattern) {
			$tr.before(fmdc.trrow);
		} else if ('div12'==pattern) {
			$tr.before(fmdc.trrowdiv12);
			fmdf_refreshTdWidth($tr.prev(), pattern);
		}
		$tr.prev().find('.fmdtd').droppable(fmdc.droppable_args).attr("id", fmdf_uiid());
	}
}

//add row after selected
function fmdf_fmcontainer_block_addrowafter() {
	var $tr = fmdf_getselectedTR();
	if ($tr) {
		var pattern = $tr.parents('.fmcontainer_block').attr("fmdpattern");
		if ('table'==pattern) {
			$tr.after(fmdc.trrow);
		} else if ('div12'==pattern) {
			$tr.after(fmdc.trrowdiv12);
			fmdf_refreshTdWidth($tr.next(), pattern);
		}
		$tr.next().find('.fmdtd').droppable(fmdc.droppable_args).attr("id", fmdf_uiid());
	}
}

//add column after selected
function fmdf_fmcontainer_block_addcolbefore() {
	var $td = fmdf_getselectedTD();
	if ($td) {
		var pattern = $td.parents('.fmcontainer_block').attr("fmdpattern");
		if ('table'==pattern) {
			if ($td.parent().children().length==fmdc.collimit.table) {
				dhtmlx.message(fmd_i18n_msg_collimit+fmdc.collimit.table);
			} else {
				$td.before(fmdc.tdcell);
				$td.prev().droppable(fmdc.droppable_args).attr("id", fmdf_uiid());
				fmdf_refreshTdWidth($td.parent(), pattern);
			}
		} else if ('div12'==pattern) {
			if ($td.parent().children().length==fmdc.collimit.div12) {
				dhtmlx.message(fmd_i18n_msg_collimit+fmdc.collimit.div12);
			} else {
				$td.before(fmdc.tdcelldiv12);
				$td.prev().droppable(fmdc.droppable_args).attr("id", fmdf_uiid());
				fmdf_refreshTdWidth($td.parent(), pattern);
			}
		}
	}
}

//add column after selected
function fmdf_fmcontainer_block_addcolafter() {
	var $td = fmdf_getselectedTD();
	if ($td) {
		var pattern = $td.parents('.fmcontainer_block').attr("fmdpattern");
		if ('table'==pattern) {
			if ($td.parent().children().length==fmdc.collimit.table) {
				dhtmlx.message(fmd_i18n_msg_collimit+fmdc.collimit.table);
			} else {
				$td.after(fmdc.tdcell);
				$td.next().droppable(fmdc.droppable_args).attr("id", fmdf_uiid());
				fmdf_refreshTdWidth($td.parent(), pattern);
			}
		} else if ('div12'==pattern) {
			if ($td.parent().children().length==fmdc.collimit.div12) {
				dhtmlx.message(fmd_i18n_msg_collimit+fmdc.collimit.div12);
			} else {
				$td.after(fmdc.tdcelldiv12);
				$td.next().droppable(fmdc.droppable_args).attr("id", fmdf_uiid());
				fmdf_refreshTdWidth($td.parent(), pattern);
			}
		}
	}
}

//add column to a tr
function fmdf_fmcontainer_block_appendtd($tr, id, rowspan, colspan) {
	//$tr.append('<td class="fmdtd fmdselectable" id="'+id+'" rowspan="'+rowspan+'" colspan="'+colspan+'"></td>');
	var pattern = $tr.parents('.fmcontainer_block').attr("fmdpattern");
	var $td = null;
	if ('table'==pattern) {
		if ($tr.children().length==fmdc.collimit.table) {
			dhtmlx.message(fmd_i18n_msg_collimit+fmdc.collimit.table);
			return null;
		}
		$tr.append(fmdc.tdcell0);
		$td = $tr.find('.fmdtd:last').droppable(fmdc.droppable_args)
			.attr("rowspan", rowspan || '1').attr("colspan", colspan || '1').attr("id", id);
	} else if ('div12'==pattern) {
		if ($tr.children().length==fmdc.collimit.div12) {
			dhtmlx.message(fmd_i18n_msg_collimit+fmdc.collimit.div12);
			return null;
		}
		$tr.append(fmdc.tdcell0div12);
		$td = $tr.find('.fmdtd:last').attr('fmdcols', colspan||'12').droppable(fmdc.droppable_args).attr("id", id);
	}
	fmdf_refreshTdWidth($tr);
	return $td;
}

//get the row contains the selected object
function fmdf_getselectedTR() {
	var $tr = null;
	if ( fmdf_hasClass($(fmdc.selection.selectedobj).parent(), 'ui-droppable') ) {//element selected
		$tr = $(fmdc.selection.selectedobj).parent().parent();
	} else if ( fmdf_hasClass(fmdc.selection.selectedobj, 'ui-droppable') ) {//td selected
		$tr = $(fmdc.selection.selectedobj).parent();
		//console.debug('td selected');
	}/*  else if (fmdf_hasClass($(fmdc.selection.selectedobj), 'fmcontainer_block_row')) {//tr selected
		$tr = $(fmdc.selection.selectedobj);
	} */
	return $tr;
}

//get the row contains the selected object
function fmdf_getselectedTD() {
	if (!fmdc.selection.selectedobj) return null;
	var $td = null;
	if ( fmdf_hasClass($(fmdc.selection.selectedobj).parent(), 'ui-droppable') ) {//element selected
		$td = $(fmdc.selection.selectedobj).parent();
	} else if ( fmdf_hasClass(fmdc.selection.selectedobj, 'ui-droppable') ) {//td selected
		$td = $(fmdc.selection.selectedobj);
	}
	return $td;
}

//reset td width by setting class
function fmdf_refreshTdWidth($tr, pattern, deleting) {
	//console.debug('$tr.children().length='+$tr.children().length);
	pattern || (pattern = $tr.parents('.fmcontainer_block').attr("fmdpattern"));
	var $tds = $tr.find('.fmdtd');
	var cnum = $tds.length;
	if (cnum>0) {
		if ('table'==pattern) {
			//get max total spans for all rows
			var maxspans = fmdf_getMaxCols($tr.parent());
			//set class
			$tr.parent().find('.fmdtd').each(function () {//all rows
				var span = $(this).attr('colSpan');
				var width = parseInt(100/maxspans*(span==undefined ? 1 : parseInt(span)))+'%';
				//console.debug('set cell width='+width);
				$(this).css('width', width);
			});
		} else if ('div12'==pattern) {
			var atomw = ($tr.width() - cnum*4)*100/$tr.width()/12;//4 for (margin 1px and border 1px)*2
			var cols = parseInt(12/cnum);
			var totalcolspan = 0;
			$tds.each(function () {//current row only
				//console.debug('set cell width='+(atomw*cols+'%'));
				var colspan = $(this).attr('fmdcols');
				colspan = fmd.isloading ? parseInt(colspan || 12) : cols;
				totalcolspan += colspan;
				$(this).attr('fmdcols', colspan).css('width', (atomw*colspan+'%'));
			});
			if (totalcolspan>12) {	//reset
				$tds.each(function () {//current row only
					//console.debug('set cell width='+(atomw*cols+'%'));
					$(this).attr('fmdcols', cols).css('width', (atomw*cols+'%'));
				});
			}
			if (deleting) fmdf_refreshCellHeightDiv12($tr);
		}
	}
}

//reset td width by setting class
function fmdf_refreshCellHeightDiv12($tr) {
	//console.debug('$tr.children().length='+$tr.children().length);
	var cnum = $tr.children().length;
	if (cnum>0) {
		var h = 0;
		var cells = $tr.find('.fmdtd');
		for(var i=0; i<cells.length; i++) {
			if ($(cells[i]).children('.fmddropped').length>0) {
				$(cells[i]).height($(cells[i]).children().eq(0).height());
			} else {
				//$(cells[i]).height($(cells[i]).css("min-height"));
				$(cells[i]).css("height", "auto");
			}
			h = $(cells[i]).height() > h ? $(cells[i]).height() : h;
			//alert($(cells[i]).height()+"====="+h);
		}
		//alert("h====="+h);
		cells.height(h);
	}
}

//get max cols of a table block
function fmdf_getMaxCols($table) {
	var maxspans = 0;
	$table.children().each(function (i, tr1) {
		var spans = 0;
		$(tr1).children().each(function (j, td1) {
			var span = $(td1).attr('colSpan');
			//console.debug('colspan='+span);
			spans += span==undefined ? 1 : parseInt(span);
		});
		if (spans>maxspans) maxspans = spans;
	});
	//console.debug('maxspans='+maxspans);
	return maxspans;
}

//check if the className exists on dom object
function fmdf_hasClass($obj, className) {
	//return $obj.hasClass(className);
	return $obj && $obj.is("."+className);
}

//get dropped element component type and type
function fmdf_getElemCompTypes($obj) {
	var rtn = {};
	if (fmdf_hasClass($obj, 'fmdcanvas_tabnavli')){
		rtn.compType = 'layout';
		rtn.type = 'tab';
	} else if (fmdf_hasClass($obj, 'fmcontainer_block')) {
		rtn.compType = 'layout';
		rtn.type = 'block';
	} else if (fmdf_hasClass($obj, 'ui-droppable')) {
		rtn.compType = 'layout';
		rtn.type = 'cell';
	} else if (fmdf_hasClass($obj, 'fmddropped')) {
		rtn.compType = 'control';
		rtn.type = fmdf_getElemType($obj);
	}
	return rtn;
}

//get dropped element type
function fmdf_getElemType($obj) {
	var cls = $obj.attr('class');
	var idx = cls.indexOf('fmdelement_');
	cls = cls.substr(idx+11);
	if (cls.indexOf(' ')!=-1) {
		cls = cls.substring(0, cls.indexOf(' '));
	}
	//console.debug("element class==="+cls+"===");
	return cls;
}

//select an dom object
function fmdf_select($obj) {
	fmdf_unselect();
	$($obj).addClass('fmdselected');
	//console.debug($($obj).attr('class'));
	fmdc.selection.selectedobj = $obj;
	//set status bar
	fmdf_setselectedstatus($obj);
}

//select an dom object by id
function fmdf_selectById(id) {
	var $obj = $("#"+id);
	$obj.length && fmdf_select($obj);
}

//get selected object
function fmdf_getSelected() {
	return fmdc.selection.selectedobj;
}

//deselect object
function fmdf_unselect($obj) {
	var obj = $obj;
	//console.debug($obj);
	if (!obj) {
		//console.debug('fmdc.selection.selectedobj='+fmdc.selection.selectedobj);
		obj = fmdc.selection.selectedobj;
	}
	if (obj) {
		//console.debug('remove class');
		$(obj).removeClass('fmdselected');
		fmdc.selection.selectedobj = null;
		//set status bar
		fmdc.statusbar.setText('');
		//clean properties data
		fmdpf_clear_elemprop();
	}
}

//on removed
function fmdf_onremove() {
	$('.fmdselected').removeClass('fmdselected');
	fmdc.selection.selectedobj = null;
	//set status bar
	fmdc.statusbar.setText('');
	//clean properties data
	fmdpf_clear_elemprop();
}

//set selected status
function fmdf_setselectedstatus($obj) {
	//init properties data
	var id1 = $obj.attr('id');
	if (id1 && !fmdc.version.formdata.propconf[id1]) fmdc.version.formdata.propconf[id1] = {};
	//status
	var status = '';//fmd_i18n_msg_curselected + ': ';
	if (fmdf_hasClass($obj, 'fmdcanvas_tabnavli')){
		//status += fmd_i18n_l_fmcontainer_tab + '   ' + $obj.find('a').html();
		//fmdc.cell_prop_tb.enableItem('fmd_cb_apply');//enable apply button
		fmdpf_showprop('layout', 'tab', $obj);
	} else if (fmdf_hasClass($obj, 'fmcontainer_block')) {
		//status += fmd_i18n_l_fmcontainer_block + '   ' + $obj.find('.fmcontainer_block_titlebar a b').text();
		//fmdc.cell_prop_tb.enableItem('fmd_cb_apply');//enable apply button
		fmdpf_showprop('layout', 'block', $obj);
	} else if (fmdf_hasClass($obj, 'ui-droppable')) {
		/*var cspan = $obj.attr('colSpan');
		var rspan = $obj.attr('rowSpan');
		status += fmd_i18n_l_fmcontainer_cell + 
			'   '+fmd_i18n_t_colspan+'='+ 
			(cspan==undefined?1:cspan) + 
			'   '+fmd_i18n_t_rowspan+'='+
			(rspan==undefined?1:rspan);*/
		//fmdc.cell_prop_tb.disableItem('fmd_cb_apply');//disable apply button
		fmdpf_showprop('layout', 'cell', $obj);
	} else if (fmdf_hasClass($obj, 'fmddropped')) {
		//status += fmd_i18n_l_elem;
		//fmdc.cell_prop_tb.enableItem('fmd_cb_apply');//enable apply button
		//show prop
		fmdpf_showprop('control', fmdf_getElemType($obj), $obj);
	} else {
		//fmdc.cell_prop_tb.disableItem('fmd_cb_apply');//disable apply button
	}
	//update status bar
	fmdc.statusbar.setText(status);
}

//find object and focus
function fmdf_findto(id1) {
	fmdc.popup_finddom.hide();
	var $obj = $('.fmdcanvas #'+id1);
	//alert($obj);
	if ($obj.length) {
		$obj.focus();
		$obj.effect("highlight", {}, 1000, function(){fmdf_select($obj);});
	} else {
		dhtmlx.message(fmd_i18n_msg_notfound);
	}
}

//remove selected object
function fmdf_removeselected() {
	if (fmd.tabbar.getActiveTab()!="fmdtab_canvas") return;
	if (fmdc.selection.selectedobj) {
		//check if parent need to be removed
		var parent1 = $(fmdc.selection.selectedobj).parent();
		var fmdpattern = $(fmdc.selection.selectedobj).parents('.fmcontainer_block').attr("fmdpattern");
		var $ptr = null;
		var $also = null;
		var $selectobjafter = null;
		if ( fmdf_hasClass(fmdc.selection.selectedobj, 'ui-droppable') ) {//remove td
			//console.debug('==='+parent1.children().length);
			if(parent1.children().length==1) {
				$also = parent1;
			} else {
				fmdf_refreshTdWidth(parent1, null, true);//refresh td width
				$ptr = parent1;
			}
		} else if ( fmdf_hasClass(parent1, 'ui-droppable') ) {//remove element
			//just replace with p tag
			parent1.find('.fmddropped').length==1 && parent1.append(fmdc.tipp);//last one
			//parent1.removeClass('ui-state-highlight');
			//select parent
			$selectobjafter = parent1;
			$ptr = $(fmdc.selection.selectedobj).parents('.fmdtr');
		} else if (fmdf_hasClass(fmdc.selection.selectedobj, 'fmdcanvas_tabnavli')) {
			fmdf_removeselectedtab();
			return;
		} else if (fmdf_hasClass(fmdc.selection.selectedobj, 'fmcontainer_block')) {
			fmdf_removeselectedcontainer();
			return;
		}
		//删除
		//delete fmdc.version.formdata.propconf[$(fmdc.selection.selectedobj).attr("id")];
		$(fmdc.selection.selectedobj).hide("fade",300).remove();
		//unselect
		fmdf_onremove();
		//remove parent also
		if ($also) {
			console.debug('parent tr also removed.');
			$also.remove();
		}
		//reset div12 cell heights
		if ('div12'==fmdpattern && $ptr) {
			fmdf_refreshCellHeightDiv12($ptr);
		}
		//select some obj after remove
		if ($selectobjafter) {
			fmdf_select($selectobjafter);
		} else {
			//set status bar
			fmdc.statusbar.setText('');
		}
	}
}

//delete current tab
function fmdf_removeselectedtab() {
	var activetab = fmdc.tabs.find(".ui-tabs-active");
	if (activetab) {
		var tabcontent = $('#'+activetab.attr('aria-controls'));
		if (tabcontent.find('.fmform').children().length>0) {
			dhtmlx.message({
				type:"confirm",
	            ok:fmd_i18n_b_ok,
	            cancel:fmd_i18n_b_cancel,
				text: fmd_i18n_msg_deltabconfirm,
				callback: function(yes) {
					if (yes) {
						//delete fmdc.version.formdata.propconf[$(fmdc.selection.selectedobj).attr("id")];
						activetab.remove();
						tabcontent.remove();
						fmdc.tabs.tabs( "refresh" );
						fmdf_onremove();
					}
				}
			});
		} else {
			//delete fmdc.version.formdata.propconf[$(fmdc.selection.selectedobj).attr("id")];
			activetab.remove();
			tabcontent.remove();
			fmdc.tabs.tabs( "refresh" );
			fmdf_onremove();
		}
	}
}

//remove container
function fmdf_removeselectedcontainer() {
	if (fmdc.selection.selectedobj.find('.fmddropped').children().length>0) {
		dhtmlx.message({
			type:"confirm",
            ok:fmd_i18n_b_ok,
            cancel:fmd_i18n_b_cancel,
			text: fmd_i18n_msg_delcontconfirm,
			callback: function(yes) {
				if (yes) {
					//删除
					//delete fmdc.version.formdata.propconf[$(fmdc.selection.selectedobj).attr("id")];
					$(fmdc.selection.selectedobj).remove();
					//unselect
					fmdf_onremove();
				}
			}
		});
	} else {
		//删除
		//delete fmdc.version.formdata.propconf[$(fmdc.selection.selectedobj).attr("id")];
		$(fmdc.selection.selectedobj).remove();
		//unselect
		fmdf_onremove();
	}
}

//mark element as copied
function fmdf_markCopy() {
	if (fmd.tabbar.getActiveTab()!="fmdtab_canvas") return;
	if (document.activeElement.type && document.activeElement.type.indexOf('text')>=0
			&& $(document.activeElement).parents('.fmdcanvaswrapper').length==0 ) {
		return;
	}
	var classes = fmdf_getSelected().attr("class").split(" ");
	for (var i in classes) {
		if (classes[i]=="fmddropped") {
			fmdc.tempCopy = {"id":fmdf_getSelected().attr("id"),
					"type" : "fmddropped",
					"html": fmdf_getSelected()[0].outerHTML};
			msg(fmd_i18n_msg_elemcopied+":&nbsp;"+fmdc.tempCopy.id);
			break;
		} else if (classes[i]=="fmcontainer_block") {
			fmdc.tempCopy = {"id":fmdf_getSelected().attr("id"),
					"type" : "fmcontainer_block",
					"html": fmdf_getSelected()[0].outerHTML};
			msg(fmd_i18n_msg_elemcopied+":&nbsp;"+fmdc.tempCopy.id);
			break;
		}
	}
}

//mark element as copied
function fmdf_doCopy() {
	//在html string中去掉id属性
	function fmdf_trimIdInHtmlStr(htmlstr) {
		var i1 = htmlstr.indexOf('id=');
		while(i1>=0) {
			var i2 = htmlstr.indexOf(' ', i1);
			htmlstr = htmlstr.substr(0, i1) + htmlstr.substr(i2+1);
			i1 = htmlstr.indexOf('id=');
		}
		return htmlstr;
	}
	
	if (fmdc.tempCopy && fmdc.tempCopy.id) {
		if (fmdc.tempCopy.type=="fmddropped") {
			if (fmdf_getSelected().find('.fmddropped').length>0) {
				msg(fmd_i18n_msg_delexistingfirst);
			} else if (fmdf_hasClass(fmdf_getSelected(), "fmdtd")) {
				var htmlstr = fmdc.tempCopy.html;
				fmdf_getSelected().empty().append(fmdf_trimIdInHtmlStr(htmlstr));
				var newelem = fmdf_getSelected().find(".fmddropped:last");
				newelem.attr("id", fmdf_uiid());
				fmdf_select(newelem);
			}
		} else if (fmdc.tempCopy.type=="fmcontainer_block") {
			var activetab = fmdc.tabs.find(".ui-tabs-active");
			if (activetab) {
				var tabcontent = $('#'+activetab.attr('aria-controls'));
				if(fmdf_hasClass(tabcontent, 'fmbusinesstab')) {
					var htmlstr = fmdc.tempCopy.html;
					tabcontent.find('.fmform').append(fmdf_trimIdInHtmlStr(htmlstr));
					var id1 = "fmcontainer_block_"+ fmdc.contidx++;
					var block = tabcontent.find( ".fmcontainer_block:last" ).attr("id", id1);
					block.hide().show("slide", {}, 300, null );
					block.find('.fmdtd').each(function(){
						$(this).droppable(fmdc.droppable_args).attr("id", fmdf_uiid());
						fmdf_select($(this));
					});
					block.find('.fmddropped').each(function(){
						$(this).attr("id", fmdf_uiid());
						fmdf_select($(this));
					});
					fmdf_select(block);
				}
			}
		}
	}
	
}

//onresize
function fmdf_onresize() {
	fmd.body_layout && fmd.body_layout.setSizes();
}

//function for init layout
function fmdf_initLayout() {
	fmd.body_layout = new dhtmlXLayoutObject('fmdmaindiv', '1C', dhx_skin);
	
	fmdf_wait(1);
	
	fmd.body_layout.attachEvent("onResizeFinish", function(){
		
	});
	
	//form designer layout
	fmdf_initDesignerLayout(fmd.body_layout);
	
}

//init designer layout
function fmdf_initDesignerLayout(body_layout) {
	
	var fmd_layout = body_layout.cells('a').attachLayout('1C', dhx_skin);

	//main tool bar
	var fmd_tb = fmd_layout.attachToolbar();
	fmd_tb.setIconSize(24);
	fmd_tb.setIconsPath(fmdc.imagepath);
	
	fmd_tb.addButton('fmd_mcb_close',0,fmd_i18n_b_close,"close.png","close_dis.png");
	!fmd.isEditor && fmd_tb.addText('fmd_mcb_t0',0,'<span class="fmdcanvastip"><img style="vertical-align:middle;" src="'+fmdc.imagepath+'/readonly1.png"/>'+fmd_i18n_msg_readonly+'</span>');
	//show advanced view button
	if (fmd.advanced) {
		fmd_tb.addText('fmd_mcb_t1',0,'&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;');
		fmd_tb.addSeparator('fmd_mcb_sp1',0);
		fmd_tb.addButtonTwoState('fmd_mcb_showadvanced', 0, fmd_i18n_b_showadvanced_dis, "showadvanced_dis.png");
	}
	//fmd.isEditor && fmd_tb.addButton('fmd_mcb_console',0,fmd_i18n_b_console,"consoleinfo.png","consoleinfo_dis.png");
	fmd_tb.addText('fmd_mcb_t2',0,'&nbsp;&nbsp;');
	fmd_tb.addSeparator('fmd_mcb_sp2',0);
	fmd_tb.addButton('fmd_mcb_restore',0,fmd_i18n_b_restore,"restore.png","restore_dis.png");
	fmd_tb.addButton('fmd_mcb_reset',0,fmd_i18n_b_reset,"reset.png","reset_dis.png");
	fmd.printEnabled && fmd_tb.addButton('fmd_mcb_printpreview',0,fmd_i18n_b_printpreview,"printpreview.png","printpreview_dis.png");
	fmd_tb.addButton('fmd_mcb_preview',0,fmd_i18n_b_preview,"preview.gif","preview_dis.gif");
	fmd_tb.addButton('fmd_mcb_save',0,fmd_i18n_b_save,"save.gif","save_dis.gif");
	fmd_tb.addSpacer(fmd.isEditor ? 'fmd_mcb_t1':'fmd_mcb_t0');
	
	if (!fmd.isEditor) {
		fmd_tb.hideItem('fmd_mcb_save');
		fmd_tb.hideItem('fmd_mcb_reset');
		fmd_tb.hideItem('fmd_mcb_restore');
	}
	
	//main tool bar events
	fmd_tb.attachEvent("onClick", function(tbid){
		if ("fmd_mcb_close"==tbid) {
			if (fmdc.unsavedchange) {
				dhtmlx.message({
					type:"confirm",
		            ok:fmd_i18n_b_ok,
		            cancel:fmd_i18n_b_cancel,
					text: fmd_i18n_msg_unsavedchange,
					callback: function(yes) {
						if (yes) {
							closeWin();
						}
					}
				});
			} else {
				closeWin();
			}
			
		} else if ("fmd_mcb_save"==tbid) {
			fmdf_save();
		} else if ("fmd_mcb_preview"==tbid) {
			fmd_preview('preview', 'generatePreview');
		} else if ("fmd_mcb_printpreview"==tbid) {
			fmd_preview('printpreview', 'generatePrintPreview');
		} else if ("fmd_mcb_reset"==tbid) {
			if (fmdc.unsavedchange) {
				dhtmlx.message({
					type:"confirm",
		            ok:fmd_i18n_b_ok,
		            cancel:fmd_i18n_b_cancel,
					text: fmd_i18n_msg_unsavedchange,
					callback: function(yes) {
						if (yes) {
							fmdf_cleanCanvas();
							if (fmdc.form.formid && fmdc.version.formdata) {
								fmdf_wait(1);
								$.when(fmdf_loadSavedData()).done(function(){
									fmdf_wait(0);
								});
							} else {
								fmdf_resetVars();
							}
						}
					}
				});
			} else {
				fmdf_cleanCanvas();
				if (fmdc.form.formid && fmdc.version.formdata) {
					fmdf_wait(1);
					$.when(fmdf_loadSavedData()).done(function(){
						fmdf_wait(0);
					});
				} else {
					fmdf_resetVars();
				}
			}
		} else if ("fmd_mcb_restore"==tbid) {
			fmdf_showVersionHistory();
		}
	});
	
	//cells
	var a = fmd_layout.cells('a');
	a.setText(fmd_i18n_t_formconfig);
	a.hideHeader();
	
	//tabbar
	fmd.tabbar = a.attachTabbar();
	//fmd.tabbar.setMargin(2);
	
	//
	fmd_tb.attachEvent("onStateChange", function(tbid, state){
		if ('fmd_mcb_showadvanced'==tbid) {
			fmdc.advancedview = state;
			fmdf_setAdvancedView(state);
		}
	});
	//init state
	fmdc.fmd_tb = fmd_tb;
	
	//tab page -- basic info
	fmdf_initBasicLayout();
	
	
	//tab page canvas
	fmdf_initCanvasLayout();
	
	
	//tab page -- feature
	//fmdf_initFeatureLayout();

	
	//tab page -- permission
	//fmdf_initPermissionLayout();
	
	
	//tab page -- reference
	fmdf_initReferenceLayout();


	//tab page -- script
	fmdf_initScriptLayout();
}

//init basic info tab page
function fmdf_initBasicLayout() {
	fmd.tabbar.addTab('fmdtab_basic', '<img src="'+fmdc.imagepath+'info.png" align="absmiddle"/>&nbsp;'+fmd_i18n_t_formbaisc,'');
	var fmdtab_basic = fmd.tabbar.cells('fmdtab_basic');
	fmd.tabbar.tabs('fmdtab_basic').setActive();
	//alert('fmdc.form='+JSON.stringify(fmdc.form));
	var fmdtab_basic_str = [
	   		{ type:"fieldset" , name:"fieldset_formbasic", label:fmd_i18n_l_fm, list:[
	   		{ type:"input" , name:"fi_basic_type", label:fmd_i18n_l_fmtype, value:fmd_i18n.enu.fmtype[fmdc.form.formtype], disabled:true, labelWidth:100, inputWidth:300},
	   		{ type:"input" , name:"fi_basic_name", label:fmd_i18n_l_fmname, labelWidth:100, inputWidth:300, required:true},
	   		{ type:"input" , name:"fi_basic_desc", label:fmd_i18n_l_fmdesc, rows:"3", labelWidth:100, inputWidth:300}
	   		]  },
	   		{ type:"fieldset" , name:"fieldset_versionbasic", hidden:true, label:fmd_i18n_l_vr, list:[
	   		{ type:"input" , name:"fi_basic_vname", label:fmd_i18n_l_vrname, labelWidth:100, inputWidth:300, required:true},
	   		{ type:"input" , name:"fi_basic_vdesc", label:fmd_i18n_l_vrdesc, rows:"3", labelWidth:100, inputWidth:300}
	   		]  }
	   	];
	//fmdc.form_basic = fmdtab_basic.attachForm(fmdtab_basic_str);
	fmdtab_basic.attachHTMLString('<div id="fmdtab_basic_lo1"></div>');
	var lo1_fmdtab_basic = new dhtmlXLayoutObject("fmdtab_basic_lo1", "2E", dhx_skin);
	lo1_fmdtab_basic.cells('a').hideHeader();
	lo1_fmdtab_basic.cells('a').setHeight(310);
	lo1_fmdtab_basic.cells('a').fixSize(true, true);
	lo1_fmdtab_basic.cells('b').fixSize(true, true);
	lo1_fmdtab_basic.cells('b').setText(fmd_i18n_l_models);
	lo1_fmdtab_basic.cells('b').hideArrow();
	//$('#fmdtab_basic_lo1').find('.dhtmlxLayoutPolySplitterHorInactive').hide();
	fmdc.form_basic = lo1_fmdtab_basic.cells('a').attachForm(fmdtab_basic_str);
	
	//model list toolbar
	var tb_model = lo1_fmdtab_basic.cells('b').attachToolbar();
	tb_model.setIconsPath(fmd.imagepath);
	if (fmd.isEditor) {
		tb_model.addButton('fmd_cb_modelrefresh',0,fmd_i18n_b_refresh,"refresh.gif","refresh_dis.gif");
		tb_model.addButton('fmd_cb_modeldel',0,fmd_i18n_b_del2,"delete1.gif","delete1_dis.gif");
		tb_model.addButton('fmd_cb_modeladd',0,fmd_i18n_b_add,"new1.gif","new1_dis.gif");
	}
	
	//model list grid
	fmdc.grid_model = lo1_fmdtab_basic.cells('b').attachGrid();
	fmdc.grid_model.setHeader([fmd_i18n_l_model,fmd_i18n_l_modeldesc,fmd_i18n_l_bo_purpose],null,["text-align:center;","text-align:center;","text-align:center;"]);
	fmdc.grid_model.setInitWidths("180,230,60");
	fmdc.grid_model.setColumnIds("BONAME,BODESC,PURPOSE");
	fmdc.grid_model.setColTypes("ro,ro,pairro");
	fmdc.grid_model.setColSorting("na,na,na");
	//fmdc.grid_model.setColumnsVisibility("false,false,false");
	fmdc.grid_model.setColAlign("left,left,center");
	fmdc.grid_model.setEditable(false);
	fmdc.grid_model.setLang(fmd.lang);
	fmdc.grid_model.init();
	
	tb_model.attachEvent('onClick', function(btid) {
		if ('fmd_cb_modeladd'==btid) {
			fmdf_openSelectorModel();
		} else if ('fmd_cb_modeldel'==btid) {
			var modelName = fmdc.grid_model.getSelectedRowId();
			if (!modelName) {
				msg(fmd_i18n_msg_sel);
				return;
			}
			if (!fmdf_checkModelRef(modelName)) {
				return;
			}
//			dhtmlx.message({
//				type:"confirm",
//	            ok:fmd_i18n_b_ok,
//	            cancel:fmd_i18n_b_cancel,
//				text: fmd_i18n_msg_delmodelconfirm,
//				callback: function(yes) {
//					if (yes) {
						fmdc.grid_model.deleteRow(modelName);
						delete fmdc.models[modelName];
						fmdc.unsavedchange = true;
//					}
//				}
//			});
			
		} else if ('fmd_cb_modelrefresh'==btid) {
			fmdf_loadModelList(true);
			fmdc.unsavedchange = true;
		}
	});
	
	
}

//init canvas layout
function fmdf_initCanvasLayout() {
	//tab page -- designer canvas
	fmd.tabbar.addTab('fmdtab_canvas', '<img src="'+fmdc.imagepath+'canvas.png" align="absmiddle"/>&nbsp;'+fmd_i18n_t_formdesign,'');
	var fmdtab_canvas = fmd.tabbar.cells('fmdtab_canvas');
	var layout_canvas = fmdtab_canvas.attachLayout('2U', dhx_skin);
	var cell_canvas = layout_canvas.cells('a');
	cell_canvas.setText(fmd_i18n_t_formcanvas);
	cell_canvas.hideHeader();
	fmdc.cell_prop = layout_canvas.cells('b');
	fmdc.cell_prop.setWidth(fmdc.cell_prop_width);
	fmdc.cell_prop.setText('<img src="'+fmdc.imagepath+'fmd_prop.gif"></img>'+fmd_i18n_t_prop);
	//add toolbar for propgrid
	if (fmd.isEditor) {
		fmdc.cell_prop_tb = fmdc.cell_prop.attachToolbar();
		fmdc.cell_prop_tb.setIconsPath(fmdc.imagepath);
		fmdc.cell_prop_tb.addButton('fmd_cb_apply',0,fmd_i18n_b_apply,"apply.gif","apply_dis.gif");
		fmdc.cell_prop_tb.attachEvent("onClick", function(tbid){//do nothing,only used for trigger onChange events of form
			if(tbid=='fmd_cb_apply'){
				fmdpf_apply();
			}
		});
	}
	fmdc.cell_prop.collapse();
	
	//canvas status bar
	fmdc.statusbar = cell_canvas.attachStatusBar();
	
	//canvas toolbar
	var fmd_canvas_tb = cell_canvas.attachToolbar();
	fmd_canvas_tb.setIconsPath(fmdc.imagepath);
	
	fmd_canvas_tb.addButtonSelect('fmd_cbl_settings',0,fmd_i18n_b_settings,[
   			 ['fmd_cb_fontsize','obj',fmd_i18n_b_fontsize,'fontsize.gif', 'fontsize_dis.gif'],
   			 ['fmd_cb_canvassize','obj',fmd_i18n_b_canvassize,'canvassize.gif', 'canvassize_dis.gif']
			],
	        "settings.gif",'settings_dis.gif',"disabled",true);
	fmd_canvas_tb.addSeparator('fmd_cb_sp2',0);
	fmd_canvas_tb.addButton('fmd_cb_span',0,fmd_i18n_b_span,"changespan.gif","changespan_dis.gif");
	fmd_canvas_tb.addSeparator('fmd_cb_sp1',0);
	fmd_canvas_tb.addButton('fmd_cb_parent',0,fmd_i18n_b_goparent,"goparent.png","goparent_dis.png");
	fmd_canvas_tb.addButton('fmd_cb_finddom',0,fmd_i18n_b_finddom,"find.gif","find_dis.gif");
	fmd_canvas_tb.addSeparator('fmd_cb_sp2',0);
	fmd.imp_comp && fmd_canvas_tb.addButton('fmd_cb_import',0,fmd_i18n_b_import,"copyfrom.png","copyfrom_dis.png");
	//fmd_canvas_tb.addButton('fmd_cb_deltab',0,fmd_i18n_b_deltab,"deltab.gif","deltab_dis.gif");
	fmd_canvas_tb.addButton('fmd_cb_del',0,fmd_i18n_b_del,"delete1.gif","delete1_dis.gif");
	fmd_canvas_tb.addButtonSelect('fmd_cbl_new',0,fmd_i18n_b_newl,
			[['fmd_cb_newtab','obj',fmd_i18n_b_newtab, 'newtab.gif', 'newtab_dis.gif'],
			 //['fmd_cb_newcont','obj',fmd_i18n_b_newcont, 'newcont.png', 'newcont_dis.png'],
			 ['fmd_cb_newcont_div12','obj',fmd_i18n_b_newcont_div12, 'newcont_div12.png', 'newcont_div12_dis.png'],
			 ['fmd_cb_newrow','obj',fmd_i18n_b_newrow, 'newrow.gif', 'newrow_dis.gif'],
			 ['fmd_cb_newrowbefore','obj',fmd_i18n_b_newrowbefore, 'newrowbefore.gif', 'newrowbefore_dis.gif'],
			 ['fmd_cb_newrowafter','obj',fmd_i18n_b_newrowafter, 'newrowafter.gif', 'newrowafter_dis.gif'],
			 ['fmd_cb_newcolbefore','obj',fmd_i18n_b_newcolbefore, 'newcolbefore.gif', 'newcolbefore_dis.gif'],
			 ['fmd_cb_newcolafter','obj',fmd_i18n_b_newcolafter, 'newcolafter.gif', 'newcolafter_dis.gif']
			],
			'new1.gif','new1_dis.gif',"disabled",true);
	
	if (!fmd.isEditor) {
		fmd_canvas_tb.hideItem('fmd_cbl_new');
		fmd_canvas_tb.hideItem('fmd_cb_del');
		fmd_canvas_tb.hideItem('fmd_cb_span');
		fmd_canvas_tb.hideItem('fmd_cbl_settings');
		fmd_canvas_tb.hideItem('fmd_cb_sp2');
	}

	//canvas toobr events
	fmd_canvas_tb.attachEvent("onClick", function(tbid){
		if ('fmd_cbl_new'==tbid) {
			
			if (!fmdc.selection.selectedobj || !fmdc.selection.selectedobj[0]) {
				fmd_canvas_tb.enableItem('fmd_cb_newtab');
				fmd_canvas_tb.disableItem('fmd_cb_newcont');
				fmd_canvas_tb.disableItem('fmd_cb_newcont_div12');
				fmd_canvas_tb.disableItem('fmd_cb_newrow');
				fmd_canvas_tb.disableItem('fmd_cb_newrowbefore');
				fmd_canvas_tb.disableItem('fmd_cb_newrowafter');
				fmd_canvas_tb.disableItem('fmd_cb_newcolbefore');
				fmd_canvas_tb.disableItem('fmd_cb_newcolafter');
			} else if (fmdc.selection.selectedobj.is('.fmdcanvas_tabnavli')) {
				fmd_canvas_tb.enableItem('fmd_cb_newtab');
				fmd_canvas_tb.enableItem('fmd_cb_newcont');
				fmd_canvas_tb.enableItem('fmd_cb_newcont_div12');
				fmd_canvas_tb.disableItem('fmd_cb_newrow');
				fmd_canvas_tb.disableItem('fmd_cb_newrowbefore');
				fmd_canvas_tb.disableItem('fmd_cb_newrowafter');
				fmd_canvas_tb.disableItem('fmd_cb_newcolbefore');
				fmd_canvas_tb.disableItem('fmd_cb_newcolafter');
			} else if (fmdc.selection.selectedobj.is('.fmcontainer_block')) {
				fmd_canvas_tb.enableItem('fmd_cb_newtab');
				fmd_canvas_tb.enableItem('fmd_cb_newcont');
				fmd_canvas_tb.enableItem('fmd_cb_newcont_div12');
				fmd_canvas_tb.enableItem('fmd_cb_newrow');
				fmd_canvas_tb.disableItem('fmd_cb_newrowbefore');
				fmd_canvas_tb.disableItem('fmd_cb_newrowafter');
				fmd_canvas_tb.disableItem('fmd_cb_newcolbefore');
				fmd_canvas_tb.disableItem('fmd_cb_newcolafter');
			} else if (fmdc.selection.selectedobj.is('.fmdtd')) {
				fmd_canvas_tb.enableItem('fmd_cb_newtab');
				fmd_canvas_tb.enableItem('fmd_cb_newcont');
				fmd_canvas_tb.enableItem('fmd_cb_newcont_div12');
				fmd_canvas_tb.enableItem('fmd_cb_newrow');
				fmd_canvas_tb.enableItem('fmd_cb_newrowbefore');
				fmd_canvas_tb.enableItem('fmd_cb_newrowafter');
				fmd_canvas_tb.enableItem('fmd_cb_newcolbefore');
				fmd_canvas_tb.enableItem('fmd_cb_newcolafter');
			}
		} else if ('fmd_cb_newtab'==tbid) {
			
			fmdf_addtab(fmd_i18n_untitled, "business");
			
			/*var win_newtab = fm_createCenterWindow('win_newtab', fmd_i18n_t_newtab, 300, 200);
			var newtabfmjs = [
			          		{ type:"settings" , labelWidth:270, inputWidth:270, position:"absolute"  },
			        		{ type:"combo" , name:"fi_newtab_type", label:fmd_i18n_t_type, labelWidth:250, labelLeft:5, labelTop:5, inputLeft:5, inputTop:20, required:true, readonly:true, 
			        			options:[
                                         {text: fmd_i18n_sel_business, value: "business"},
                                         {text: fmd_i18n_sel_attachment, value: "attachment"},
                                         {text: fmd_i18n_sel_history, value: "history"},
                                         {text: fmd_i18n_sel_flowchart, value: "flowchart"}
                                ]},
                            //{ type:"input" , name:"fi_newtab_title", label:fmd_i18n_t_title, labelLeft:5, labelTop:50, inputLeft:5, inputTop:70},
			        		{ type:"button" , name:"fb_newtab_ok", value:fmd_i18n_b_ok, width:100, inputWidth:100, inputLeft:20, inputTop:120  },
			        		{ type:"button" , name:"fb_newtab_cancel", value:fmd_i18n_b_cancel, width:100, inputWidth:100, inputLeft:160, inputTop:120  }
			        	];
			var fmnewtab1 = win_newtab.attachForm(newtabfmjs);
			fmnewtab1.attachEvent("onButtonClick", function(btid){
				if (btid=='fb_newtab_ok') {
					if (!fmnewtab1.validate()) {
						return;
					}
					var tabtype = fmnewtab1.getItemValue('fi_newtab_type');
					//var tabtitle = 'business'==tabtype ? fmnewtab1.getItemValue('fi_newtab_title') : fmnewtab1.getCombo('fi_newtab_type').getSelectedText();
					var tabtitle = 'business'==tabtype ? fmd_i18n_tab_title : fmnewtab1.getCombo('fi_newtab_type').getSelectedText();
					fmdf_addtab(tabtitle, tabtype);
					fmnewtab1.unload();
					win_newtab.close();
				} else if (btid=='fb_newtab_cancel') {
					fmnewtab1.unload();
					win_newtab.close();
				}
			});
			fmnewtab1.attachEvent("onChange", function(iid, newvalue){
				if (iid=='fi_newtab_type') {
					if ('business'==newvalue) {
						fmnewtab1.showItem('fi_newtab_title');
						fmnewtab1.setRequired('fi_newtab_title', true);
						fmnewtab1.setItemFocus('fi_newtab_title');
					} else {
						fmnewtab1.hideItem('fi_newtab_title');
						fmnewtab1.setRequired('fi_newtab_title', false);
					}
				}
			});*/
			//fmnewtab1.setItemFocus('fi_newtab_title');
		} else if ('fmd_cb_newcont'==tbid) {
			fmdf_fmcontainer_block_addcontainer("table");
		} else if ('fmd_cb_newcont_div12'==tbid) {
			fmdf_fmcontainer_block_addcontainer("div12");
		} else if ('fmd_cb_newrow'==tbid) {
			fmdf_fmcontainer_block_appendrow();
		} else if ('fmd_cb_newrowbefore'==tbid) {
			fmdf_fmcontainer_block_addrowbefore();
		} else if ('fmd_cb_newrowafter'==tbid) {
			fmdf_fmcontainer_block_addrowafter();
		} else if ('fmd_cb_newcolbefore'==tbid) {
			fmdf_fmcontainer_block_addcolbefore();
		} else if ('fmd_cb_newcolafter'==tbid) {
			fmdf_fmcontainer_block_addcolafter();
		} else if ('fmd_cb_import'==tbid) {
			fmdf_importfrom();
		} else if ('fmd_cb_del'==tbid) {
			confirmWarning('', fmd_i18n_msg_delconfirm, fmd_i18n_b_ok, fmd_i18n_b_cancel, function(){
				fmdf_removeselected();
			});
		}/* else if ('fmd_cb_deltab'==tbid) {
			fmdf_removeselectedtab();
		}*/ else if ('fmd_cb_finddom'==tbid) {
			if (!fmdc.popup_finddom) {
				fmdc.popup_finddom = new dhtmlXPopup({
		            toolbar: fmd_canvas_tb,
		            id: "fmd_cb_finddom",
		            mode:"bottom"
		        });
				var form1 = fmdc.popup_finddom.attachForm([{type:"input",label:"id", name: "findid"}]);
				form1.attachEvent("onEnter", function(){
					var id1 = form1.getItemValue("findid");
					if (id1!=null && $.trim(id1)!='') {
						fmdf_findto(id1);
						form1.setItemValue("findid", '');
					}
				});
				fmdc.popup_finddom.attachEvent('onShow',function(){
					form1.setItemFocus("findid");
				});
				/*fmdc.popup_finddom.attachEvent('onBlur',function(){
					this.hide();
				});*/
				//fmdc.popup_finddom.attachHTML('aaa');
			}
			//fmdc.popup_finddom.show("fmd_cb_finddom");
		} else if(tbid=='fmd_cb_parent'){
			if (fmdf_getSelected()) {
				var p = $(fmdf_getSelected()).parents(".fmdselectable:first");
				if (p.length) {
					fmdf_select(p);
				} else {
					//go current tab
					if (!fmdf_hasClass($(fmdf_getSelected()), "ui-tabs-active")) {
						var activetab = fmdc.tabs.find(".ui-tabs-active");
						fmdf_select(activetab);
					}
				}
			}
		} else if ('fmd_cb_span'==tbid) {
			
			var $td = fmdf_getselectedTD();
			if ($td) {
				var fmdpattern = $td.parents('.fmcontainer_block').attr("fmdpattern");
				var win_changecell = fm_createCenterWindow('win_changecell', fmd_i18n_t_changecell, 300, 200);
				if ('table'==fmdpattern) {
					var cspan = $td.attr('colSpan');
					var rspan = $td.attr('rowSpan');
					var changecellfmjs = [
					          		{ type:"settings" , labelWidth:270, inputWidth:270, position:"absolute"  },
		                            { type:"input" , name:"fi_changecell_colspan", value:cspan==undefined?1:cspan, label:fmd_i18n_t_colspan, labelLeft:5, labelTop:5, inputLeft:5, inputTop:20, required:true, validate:"ValidInteger"},
		                            { type:"input" , name:"fi_changecell_rowspan", value:rspan==undefined?1:rspan, label:fmd_i18n_t_rowspan, labelLeft:5, labelTop:50, inputLeft:5, inputTop:70, required:true, validate:"ValidInteger"},
					        		{ type:"button" , name:"fb_changecell_ok", value:fmd_i18n_b_ok, width:70, inputWidth:100, inputLeft:20, inputTop:120  },
					        		{ type:"button" , name:"fb_changecell_cancel", value:fmd_i18n_b_cancel, width:70, inputWidth:100, inputLeft:160, inputTop:120  }
					        	];
					var fmchangecell1 = win_changecell.attachForm(changecellfmjs);
					fmchangecell1.attachEvent("onButtonClick", function(btid){
						if (btid=='fb_changecell_ok') {
							if (!fmchangecell1.validate()) {
								return;
							}
							var newcspan = fmchangecell1.getItemValue('fi_changecell_colspan');
							if (newcspan > fmdc.collimit.table) {
								dhtmlx.message(fmd_i18n_msg_colspanlimit + fmdc.collimit.table);
								return;
							}
							$td.attr('colSpan', newcspan);
							$td.attr('rowSpan', fmchangecell1.getItemValue('fi_changecell_rowspan'));
							//set status bar
							fmdf_select($td);
							fmchangecell1.unload();
							win_changecell.close();
						} else if (btid=='fb_changecell_cancel') {
							fmchangecell1.unload();
							win_changecell.close();
						}
					});
					fmchangecell1.setItemFocus('fi_changecell_colspan');
				} else if ('div12'==fmdpattern) {
					var fmdcols = $td.attr('fmdcols');
					var changecellfmjs = [
					          		{ type:"settings" , labelWidth:270, inputWidth:270, position:"absolute"  },
		                            { type:"input" , name:"fi_changecell_colspan", value:fmdcols==undefined?12:fmdcols, label:fmd_i18n_t_colspan, labelLeft:5, labelTop:5, inputLeft:5, inputTop:20, required:true, validate:"ValidInteger"},
					        		{ type:"button" , name:"fb_changecell_ok", value:fmd_i18n_b_ok, width:70, inputWidth:100, inputLeft:20, inputTop:120  },
					        		{ type:"button" , name:"fb_changecell_cancel", value:fmd_i18n_b_cancel, width:70, inputWidth:100, inputLeft:160, inputTop:120  }
					        	];
					var fmchangecell1 = win_changecell.attachForm(changecellfmjs);
					fmchangecell1.attachEvent("onButtonClick", function(btid){
						if (btid=='fb_changecell_ok') {
							if (!fmchangecell1.validate()) {
								return;
							}
							var newcspan = fmchangecell1.getItemValue('fi_changecell_colspan');
							var allcols = 0;
							var sb1 = $td.siblings();
							if (sb1.length>0) {
								for (var i=0; i<sb1.length; i++) {
									allcols += parseInt($(sb1[i]).attr('fmdcols'));
								}
							}
							var collimit = 12 - allcols;
							if (parseInt(newcspan) > collimit) {
								dhtmlx.message(fmd_i18n_msg_colspanlimit + collimit + '</br>' +
										fmd_i18n_msg_fmdcolslimit + 12);
								return;
							}
							$td.attr('fmdcols', newcspan);
							var $tr = $td.parent();
							var atomw = ($tr.width() - $tr.children().length*4)*100/$tr.width()/12;//4 for (margin 1px and border 1px)*2
							$td.css('width', (atomw*parseInt(newcspan)+'%'));
							//set status bar
							fmdf_select($td);
							fmchangecell1.unload();
							win_changecell.close();
						} else if (btid=='fb_changecell_cancel') {
							fmchangecell1.unload();
							win_changecell.close();
						}
					});
					fmchangecell1.setItemFocus('fi_changecell_colspan');
				}
			}
			
		} else if ('fmd_cb_canvassize'==tbid) {
			var win_canvassize = fm_createCenterWindow('win_canvassize', fmd_i18n_t_canvassize, 300, 200);
			var canvassizefmjs = [
			          		{ type:"settings" , labelWidth:270, inputWidth:270, position:"absolute"  },
                            { type:"input" , name:"fi_canvassize_widthem", value:fmdc.canvas_size_widthem, label:fmd_i18n_t_widthem, labelLeft:5, labelTop:5, inputLeft:5, inputTop:20, required:true, validate:"ValidInteger"},
			        		{ type:"button" , name:"fb_canvassize_ok", value:fmd_i18n_b_ok, width:70, inputWidth:100, inputLeft:20, inputTop:120  },
			        		{ type:"button" , name:"fb_canvassize_cancel", value:fmd_i18n_b_cancel, width:70, inputWidth:100, inputLeft:160, inputTop:120  }
			        	];
			var fmcanvassize1 = win_canvassize.attachForm(canvassizefmjs);
			fmcanvassize1.attachEvent("onButtonClick", function(btid){
				if (btid=='fb_canvassize_ok') {
					if (!fmcanvassize1.validate()) {
						return;
					}
					//TODO
					//console.debug('fmdcanvas before change width is '+$('.fmdcanvas').css('width'));
					fmdc.canvas_size_widthem = fmcanvassize1.getItemValue('fi_canvassize_widthem');
					$('.fmdcanvas').css('width', fmdc.canvas_size_widthem+'em');
					//console.debug('fmdcanvas after change width is '+$('.fmdcanvas').css('width'));
					fmcanvassize1.unload();
					win_canvassize.close();
				} else if (btid=='fb_canvassize_cancel') {
					fmcanvassize1.unload();
					win_canvassize.close();
				}
			});
			fmcanvassize1.setItemFocus('fi_canvassize_widthem');
		} else if ('fmd_cb_fontsize'==tbid) {
			var win_fontsize = fm_createCenterWindow('win_fontsize', fmd_i18n_t_fontsize, 300, 200);
			var fontsizefmjs = [
			          		{ type:"settings" , labelWidth:270, inputWidth:270, position:"absolute"  },
                            { type:"input" , name:"fi_fontsize_px", value:fmdc.fontsize, label:fmd_i18n_t_fontsize, labelLeft:5, labelTop:5, inputLeft:5, inputTop:20, required:true, validate:"ValidInteger"},
			        		{ type:"button" , name:"fb_fontsize_ok", value:fmd_i18n_b_ok, width:70, inputWidth:100, inputLeft:20, inputTop:120  },
			        		{ type:"button" , name:"fb_fontsize_cancel", value:fmd_i18n_b_cancel, width:70, inputWidth:100, inputLeft:160, inputTop:120  }
			        	];
			var fmfontsize1 = win_fontsize.attachForm(fontsizefmjs);
			fmfontsize1.attachEvent("onButtonClick", function(btid){
				if (btid=='fb_fontsize_ok') {
					if (!fmfontsize1.validate()) {
						return;
					}
					//TODO
					fmdc.fontsize = fmfontsize1.getItemValue('fi_fontsize_px');
					$('body').css('font-size', fmdc.fontsize+'px');
					//console.debug('font size changed to '+$('body').css('font-size'));
					fmfontsize1.unload();
					win_fontsize.close();
				} else if (btid=='fb_fontsize_cancel') {
					fmfontsize1.unload();
					win_fontsize.close();
				}
			});
			fmfontsize1.setItemFocus('fi_fontsize_px');
		}
	});
	
	//Availabel elements
	fmdf_initCanvas(layout_canvas);
}

//init elements
function fmdf_initCanvas(layout_canvas) {
	var cell_canvas = layout_canvas.cells('a');
	cell_canvas.attachHTMLString('<div class="fmdelementlistwrapper"><div class="fmdelementlist"></div></div><div class="fmdcanvaswrapper"><div id="fmdcanvas" class="fmdcanvas '+fmdc.theme+'"><ul class="fmdcanvas_tabnav"></ul></div></div>');
	//add all elements
	//construct element li list for dragging
	var elemliststr = '<div class="fmdelementlistacc">';
	//basic
	var ul_basic = '<ul>';
	//composite
	var ul_composite = '<ul>';
	//extended
	var ul_extended = '<ul>';
	var excludes = [];
	if (fmd.moduleExcludes) {
		excludes = fmd.moduleExcludes.split(",");
		for (var i in excludes) {
			if (excludes[i].indexOf('.')>-1) excludes[i] = excludes[i].split('.')[1];
		}
	}
	for (var c in fmdmeta_prop.control) {
		if (excludes.indexOf(c)>-1) {
			continue;
		}
		var icon = fmdmeta_prop.control[c].icon || 'elem_default.png';
		fmdmeta_prop.control[c].group=="basic" && (ul_basic += '<li><a href="" class="fmdraggable element-tag-'+c+'" onclick="return false;"><img src="'+fmd.moduleiconpath+icon+'"/>'+fmdmeta_prop.control[c].i18ntype+'</a></li>');
		fmdmeta_prop.control[c].group=="composite" && (ul_composite += '<li><a href="" class="fmdraggable element-tag-'+c+'" onclick="return false;"><img src="'+fmd.moduleiconpath+icon+'"/>'+fmdmeta_prop.control[c].i18ntype+'</a></li>');
		fmdmeta_prop.control[c].group=="extended" && (ul_extended += '<li><a href="" class="fmdraggable element-tag-'+c+'" onclick="return false;"><img src="'+fmd.moduleiconpath+icon+'"/>'+fmdmeta_prop.control[c].i18ntype+'</a></li>');
	}
	ul_basic += '</ul>';
	ul_composite += '</ul>';
	ul_extended += '</ul>';
	elemliststr += '<h4>'+fmd_i18n_l_elembasic+'</h4><div>'+ul_basic+'</div>';
	elemliststr += '<h4>'+fmd_i18n_l_elemcomposite+'</h4><div>'+ul_composite+'</div>';
	elemliststr += '<h4>'+fmd_i18n_l_elemextended+'</h4><div>'+ul_extended+'</div>';
	elemliststr += '</div>';
	$('.fmdelementlist').append(elemliststr);
	$(function() {
		$( ".fmdelementlistacc" ).accordion({
			heightStyle: "fill"
		});
	});
	//draggable
	$( ".fmdelementlist ul li a" ).draggable(fmdc.draggable_args);
	
	//add resize event to layout_canvas
	layout_canvas.attachEvent("onResizeFinish", function(){
		$( ".fmdelementlistacc" ).accordion("refresh");
	});
	
	//bind change event
	$('.fmdcanvas').bind('DOMNodeInserted DOMNodeRemoved', function() { 
		fmdc.unsavedchange = true;
	});
	
	//hide for readonly
	!fmd.isEditor && $(".fmdelementlistwrapper").hide();
	
}

//init feature tab page
function fmdf_initFeatureLayout() {
	fmd.tabbar.addTab('fmdtab_feature',fmd_i18n_t_formfeature,'');
	var fmdtab_features = fmd.tabbar.cells('fmdtab_feature');
}

//init permission tab page
function fmdf_initPermissionLayout() {
	fmd.tabbar.addTab('fmdtab_permission', '<img src="'+fmdc.imagepath+'permission.png" align="absmiddle"/>&nbsp;'+fmd_i18n_t_formpermission,'');
	var fmdtab_permission = fmd.tabbar.cells('fmdtab_permission');
	//fmd.tabbar.cells('fmdtab_permission').hide();
}

//init reference tab page
function fmdf_initReferenceLayout() {
	fmd.tabbar.addTab('fmdtab_ref', '<img src="'+fmdc.imagepath+'ref.png" align="absmiddle"/>&nbsp;'+fmd_i18n_t_formref,'');
	var fmdtab_ref = fmd.tabbar.cells('fmdtab_ref');
	var div_refscript = document.createElement("pre");
	div_refscript.id = "editor_refscript";
	fmdtab_ref.attachObject(div_refscript);
	
	fmdf_initRefScript();
	
	//fmd.tabbar.cells('fmdtab_ref').hide();
}

//init script tab page
function fmdf_initScriptLayout() {
	fmd.tabbar.addTab('fmdtab_script', '<img src="'+fmdc.imagepath+'script.png" align="absmiddle"/>&nbsp;'+fmd_i18n_t_formscript,'');
	var fmdtab_script = fmd.tabbar.cells('fmdtab_script');
	var accordion_script = fmdtab_script.attachAccordion();
	
	var panel_bodyscript = accordion_script.addItem('panel_bodyscript', fmd_i18n_l_bodyscript);
	var div_bodyscript = document.createElement("pre");
	div_bodyscript.id = "editor_bodyscript";
	panel_bodyscript.attachObject(div_bodyscript);
	div_bodyscript.className = "ace_editor";
	
	var panel_readyscript = accordion_script.addItem('panel_readyscript',fmd_i18n_l_readyscript);
	var div_readyscript = document.createElement("pre");
	div_readyscript.id = "editor_readyscript";
	panel_readyscript.attachObject(div_readyscript);
	div_readyscript.className = "ace_editor";
	
	var panel_datareadyscript = accordion_script.addItem('panel_datareadyscript',fmd_i18n_l_datareadyscript);
	var div_datareadyscript = document.createElement("pre");
	div_datareadyscript.id = "editor_datareadyscript";
	panel_datareadyscript.attachObject(div_datareadyscript);
	div_datareadyscript.className = "ace_editor";
	
	//resize editor
	accordion_script.attachEvent("onActive", function(aid) {
		if (aid=='panel_readyscript') {
			fmdc.editor_readyscript.resize();
		} else if (aid=='panel_bodyscript') {
			fmdc.editor_bodyscript.resize();
		} else if (aid=='panel_datareadyscript') {
			fmdc.editor_datareadyscript.resize();
		}
	});
	
	panel_datareadyscript.open();
	fmdf_initDataReadyScript();
	panel_readyscript.open();
	fmdf_initReadyScript();
	panel_bodyscript.open();
	fmdf_initBodyScript();
	
	//fmd.tabbar.cells('fmdtab_script').hide();
}

//init ref script
function fmdf_initRefScript(reset) {
	if (reset) {
		fmdc.editor_refscript.destroy();
		fmdc.editor_refscript = null;
		$('#editor_refscript').parent().empty().append('<pre id="editor_refscript" class="ace_editor"></pre>');
	}
	if (!fmdc.editor_refscript) {
		//$('#editor_refscript').html(fmdc.version.formdata.refscript);
		fmdc.editor_refscript = ace.edit("editor_refscript");
		fmdc.editor_refscript.setTheme("ace/theme/tomorrow");
		fmdc.editor_refscript.getSession().setMode("ace/mode/html");
		fmdc.editor_refscript.setValue(fmdc.version.formdata.refscript);
		fmdc.editor_refscript.on("change", function(e){fmdc.unsavedchange = true;});
		!fmd.isEditor && fmdc.editor_refscript.setReadOnly(true);
	}
}

//init header script editor
function fmdf_initReadyScript(reset) {
	if (reset) {
		fmdc.editor_readyscript.destroy();
		fmdc.editor_readyscript = null;
		$('#editor_readyscript').parent().empty().append('<pre id="editor_readyscript" class="ace_editor"></pre>');
	}
	if (!fmdc.editor_readyscript) {
		//$('#editor_readyscript').html(fmdc.version.formdata.readyscript);
		fmdc.editor_readyscript = ace.edit("editor_readyscript");
		fmdc.editor_readyscript.setTheme("ace/theme/tomorrow");
		fmdc.editor_readyscript.getSession().setMode("ace/mode/javascript");
		fmdc.editor_readyscript.setValue(fmdc.version.formdata.readyscript);
		fmdc.editor_readyscript.on("change", function(e){fmdc.unsavedchange = true;});
		!fmd.isEditor && fmdc.editor_readyscript.setReadOnly(true);
	}
}

//init body script editor
function fmdf_initBodyScript(reset) {
	if (reset) {
		fmdc.editor_bodyscript.destroy();
		fmdc.editor_bodyscript = null;
		$('#editor_bodyscript').parent().empty().append('<pre id="editor_bodyscript" class="ace_editor"></pre>');
	}
	if (!fmdc.editor_bodyscript) {
		//$('#editor_bodyscript').html(fmdc.version.formdata.bodyscript);
		fmdc.editor_bodyscript = ace.edit("editor_bodyscript");
		fmdc.editor_bodyscript.setTheme("ace/theme/tomorrow");
		fmdc.editor_bodyscript.getSession().setMode("ace/mode/javascript");
		fmdc.editor_bodyscript.setValue(fmdc.version.formdata.bodyscript);
		fmdc.editor_bodyscript.on("change", function(e){fmdc.unsavedchange = true;});
		!fmd.isEditor && fmdc.editor_bodyscript.setReadOnly(true);
	}
}

//init data ready script editor
function fmdf_initDataReadyScript(reset) {
	if (reset) {
		fmdc.editor_datareadyscript.destroy();
		fmdc.editor_datareadyscript = null;
		$('#editor_datareadyscript').parent().empty().append('<pre id="editor_datareadyscript" class="ace_editor"></pre>');
	}
	if (!fmdc.editor_datareadyscript) {
		//$('#editor_datareadyscript').empty().html(fmdc.version.formdata.datareadyscript);
		fmdc.editor_datareadyscript = ace.edit("editor_datareadyscript");
		fmdc.editor_datareadyscript.setTheme("ace/theme/tomorrow");
		fmdc.editor_datareadyscript.getSession().setMode("ace/mode/javascript");
		fmdc.editor_datareadyscript.setValue(fmdc.version.formdata.datareadyscript);
		fmdc.editor_datareadyscript.on("change", function(e){fmdc.unsavedchange = true;});
		!fmd.isEditor && fmdc.editor_datareadyscript.setReadOnly(true);
	}
}

//enable/disable apply button in properties form
function fmdf_enableApply(enable) {
	enable ? fmdc.cell_prop_tb.enableItem('fmd_cb_apply'):
		fmdc.cell_prop_tb.disableItem('fmd_cb_apply');
}

//open model selector
function fmdf_openSelectorModel() {

	var w1 = fm_createCenterWindow('wid_selectModelForModelSelect',fmd_i18n_l_models, 800, 600);

	var bom = {};
	bom.rest_query = fmd.fmdCtx + "/rest/bo/query";
	
	var lo1 = w1.attachLayout("2E");
	lo1.cells('a').hideHeader();
	lo1.cells('b').hideHeader();
	lo1.cells('b').setHeight(50);
	bom.stb = lo1.cells('a').attachStatusBar();
	bom.stb.setText("<div id='id_paging_selectModel'></div>");
			
	var str1 = [{ type:"block" , name:"form_block_1", offsetLeft:(dhx_skin=="dhx_web"?"333":"343"), offsetTop:"0", 
			list:[{ type:"button" , name:"fb_ok", value:fmd_i18n_b_ok, inputTop:10}]}];
	var fm2 = lo1.cells('b').attachForm(str1);
	
	//grid
	bom.grid = lo1.cells('a').attachGrid();
	bom.grid.setHeader([i18n_bom.hd_no,
	                    "BOID",
	                    i18n_bom.hd_name,
	                    i18n_bom.hd_desc,
	                    i18n_bom.hd_purpose,
	                    i18n_bom.hd_updatetime,
	                    i18n_bom.hd_changeuser,
	                    i18n_bom.hd_changeusername,
	                    i18n_bom.hd_creator,
	                    i18n_bom.hd_creatorname,
	                    i18n_bom.hd_createtime],
	                    null,
	                    ["text-align:center;",
	                     "text-align:center;",
	                     "text-align:center;",
	                     "text-align:center;",
	                     "text-align:center;",
	                     "text-align:center;",
	                     "text-align:center;",
	                     "text-align:center;",
	                     "text-align:center;",
	                     "text-align:center;",
	                     "text-align:center;"]);
	bom.grid.attachHeader("#rspan,&nbsp;,"+
			"<input id='sr_boname' type='text' style='width:90%'/>,"+
			"<input id='sr_bodesc' type='text' style='width:90%'/>,"+
			"#rspan,#rspan,#rspan,"+
			"#rspan,"+
			"#rspan,"+
			"#rspan,"+
			"#rspan");
	bom.grid.setInitWidths("40,100,150,250,60,125,80,100,100,100,125");
	bom.grid.setColumnIds("ROW_NO,BOID,BONAME,BODESC,PURPOSE,UPDATETIME,CHANGEUSER,CHANGEUSERNAME,CREATOR,CREATORNAME,CREATETIME");
	bom.grid.setColTypes("ro,ro,ro,ro,pairro,ro,ro,ro,ro,ro,ro");
	bom.grid.setColSorting("na,str,str,str,str,str,str,str,str,str,str");
	bom.grid.setColumnsVisibility("false,true,false,false,false,false,true,false,true,false,false");
	bom.grid.setColAlign("center,left,left,left,center,center,center,left,left,left,center");
	bom.grid.setEditable(false);
	bom.grid.setLang(fmd.lang);
	bom.grid._grid_ordercolumns = [{"CREATETIME":"DESC"}];
	bom.grid.init();
	
	//paging
	bom.grid.setPagingWTMode(true,true,true,[10,20,50]);
	bom.grid.enablePaging(true,10,5,'id_paging_selectModel');
	bom.grid.setPagingSkin("toolbar", dhx_skin);
	
	bom.grid.attachEvent("onPageChanged", function(ind,fInd,lInd){
		quri_toPage(fInd+1, lInd);
	});
	//header click event
	bom.grid.attachEvent("onHeaderClick", grid_onHeaderClick);
	
	bom.grid.attachEvent("onRowDblClicked", function(rid,cid){
		rtnValue(rid);
	});
	
	fm2.attachEvent("onButtonClick", function(btid) {
		if (btid=='fb_ok') {
			var rid = bom.grid.getSelectedRowId();
			if (!rid) {
				msg(fmd_i18n_msg_sel);
				return;
			}
			rtnValue(rid);
		}
	});

	quri_toPage(1, 10);
	
	//return
	function rtnValue(rid) {
		var id = bom.grid.cells(rid, 1).getValue();
		//var name = bom.grid.cells(rid, 2).getValue();
		//var desc = bom.grid.cells(rid, 3).getValue();
		w1.close();
		fmdf_setModels(id);
		fmdf_loadModelList(true);
		fmdc.unsavedchange = true;
	}
	
	//bind header query action
	var trsr_versionname = $("#sr_boname").parents('tr:first');
	trsr_versionname.find('td').bind('click',fmdf_stopEvent);
	trsr_versionname.find('td').bind('mouseover',fmdf_stopEvent);
	$("#sr_boname").bind('keypress', bom_enterQuery);
	$("#sr_bodesc").bind('keypress', bom_enterQuery);
	
	function bom_enterQuery(e) {
		if (e.keyCode==13) {
			bom.boquery_boname = $.trim($("#sr_boname").val());
			bom.boquery_bodesc = $.trim($("#sr_bodesc").val());
			bom.grid.currentPage = 1;
			quri_toPage(1, 10);
		}
	}
	
	//query
	function quri_toPage(fromRow, toRow){
		lo1.cells('b').progressOn();
		var p = {"queryParams":{}, "fromRow":fromRow, "toRow":toRow, 
				"timezoneOffset":new Date().getTimezoneOffset(),
				"ordercolumns":JSON.stringify(bom.grid._grid_ordercolumns)};
		bom.boquery_boname && (p.queryParams.boname = bom.boquery_boname);
		bom.boquery_bodesc && (p.queryParams.bodesc = bom.boquery_bodesc);
		p.queryParams = JSON.stringify(p.queryParams);
		doPostAsyncJson(bom.rest_query, p,
				function(ret) {
					if (!ret) {
						lo1.cells('b').progressOff();
						msgErr(fmd_i18n_msg_readfail);
						return;
					}
					bom.grid.clearAllInPaging();
					grid_setI18nInfoToGridJsonByCId(bom.grid, ret, {'PURPOSE':fmd_i18n.enu.bopurpose}, 0);
					bom.grid.parse(ret, "json");
					lo1.cells('b').progressOff();
				}, 
				function() {
					lo1.cells('b').progressOff();
					msgErr(fmd_i18n_msg_readfail);
				});
		
	}
}

//function set models
function fmdf_setModels(modelId) {
	var model = doGetSyncJson(fmd.fmdCtx+"/rest/bo/"+modelId+"?check=true&timezoneOffset="+new Date().getTimezoneOffset());
	if (!model) {
		msgErr(fmd_i18n_msg_readfail);
		return;
	}
	fmdc.models[model.boname] = model;
	/*doGetAsyncJson(flvar.fmdCtx+"/rest/bo/"+modelId+"?check=true&timezoneOffset="+new Date().getTimezoneOffset(),
			function(model) {
				if (!model) {
					msgErr(fmd_i18n_msg_readfail);
					return;
				}
				fmdc.models[model.boname] = model;
			},function() {
				msgErr(fmd_i18n_msg_readfail);
			});*/
}

//display models in model list
function fmdf_loadModelList(refresh) {
	if (MyUtilJs.isEmpty(fmdc.models)) return;
	fmdc.grid_model.clearAll();
	//parse binding model list for model binding
	fmdmeta_prop.models_list_sub = [["",""]];
	fmdmeta_prop.models_list_all = [["",""]];
	//parse binding list for databinding combo
	fmdmeta_prop.model_binding_list = [["",""]];
	//reload from db
	if (refresh) {
		for (var m in fmdc.models) {
			fmdf_setModels(fmdc.models[m].boid);
		}
	}
	//refresh attrs
	for (var m in fmdc.models) {
		fmdc.grid_model.addRow(fmdc.models[m].boname, [fmdc.models[m].boname, fmdc.models[m].bodesc, fmdc.models[m].purpose+pairro_spliter+fmd_i18n_l_bo_purpose_enu[fmdc.models[m].purpose]]);
		if ("1"==fmdc.models[m].purpose) {
			fmdmeta_prop.models_list_sub.push([m, m + (fmdc.models[m].bodesc ? "["+fmdc.models[m].bodesc+"]" : "")]);
		} else if ("0"==fmdc.models[m].purpose) {
			for (var c in fmdc.models[m].attrs) {
				fmdmeta_prop.model_binding_list.push([m+"."+c, m+"."+c]);
			}
		}
		fmdmeta_prop.models_list_all.push([m, m + (fmdc.models[m].bodesc ? "["+fmdc.models[m].bodesc+"]" : "")]);
	}
	//alert("fmdmeta_prop.model_binding_list="+JSON.stringify(fmdmeta_prop.model_binding_list));
}

//check model reference and go to the control by id
function fmdf_checkModelRef(modelName) {
	if (!fmdc.version.formdata.propconf) return;
	for (var id in fmdc.version.formdata.propconf) {
		var vals = fmdc.version.formdata.propconf[id];
		if (vals) {
			for (p in vals) {
				if ((p.indexOf('binding')>-1 || p.indexOf('model')>-1) 
						&& vals[p] && vals[p].toUpperCase().indexOf(modelName.toUpperCase())>-1) {
					msg(fmd_i18n_msg_delmodelrefered+":"+id);
					fmd.tabbar.cells('fmdtab_canvas').setActive();
					fmdf_selectById(id);
					fmdpf_scrollToProp(p);
					return false;
				}
			}
		}
	}
	return true;
}

//show version history
function fmdf_showVersionHistory() {
	if (!fmdc.version || !fmdc.version.versionid) {
		msg(fmd_i18n_msg_nohis);
		return;
	}
	var win_his = fm_createCenterWindow('win_his', fmd_i18n_b_restore, 380, 560);
	var gridhis = win_his.attachGrid();
	var tbhis = win_his.attachStatusBar();
	tbhis.setText("<div id='id_paging_his'></div>");
	
	gridhis.setIconsPath(fmd.imagepath);
	gridhis.setHeader([fmd_i18n_l_no,"FORMID","VERSIONID","CHANGENO",fmd_i18n_l_updatetime,"CHANGEUSERID",fmd_i18n_l_changeusername,fmd_i18n_l_op],
			null,
			["text-align:center;","text-align:center;","text-align:center","text-align:center","text-align:center;","text-align:center;","text-align:center;","text-align:center;"]);
	gridhis.setInitWidths("40,120,120,120,125,115,115,60");
	gridhis.setColumnIds("ROW_NO,FORMID,VERSIONID,CHANGENO,UPDATETIME,CHANGEUSERID,CHANGEUSERNAME,OP");
	gridhis.setColTypes("ro,ro,ro,ro,ro,ro,ro,ro");
	gridhis.setColSorting("na,str,str,str,str,str,str,str");
	gridhis.setColumnsVisibility("false,true,true,true,false,true,false,false");
	gridhis.setColAlign("center,left,left,left,center,center,center,center");
	gridhis.setEditable(false);
	gridhis.setLang(fmd.lang);
	gridhis.init();
	
	//default order by
	gridhis._grid_ordercolumns = [{"UPDATETIME":"DESC"}];
	
	//paging
	gridhis.setPagingWTMode(true,true,true,[20,50,100]);
	gridhis.enablePaging(true,20,5,'id_paging_his');
	gridhis.setPagingSkin("toolbar", dhx_skin);
	
	/*gridhis.attachEvent("onPageChanged", function(ind,fInd,lInd){
		gridhis_toPage(fInd+1, lInd);
	});*/
	
	//header click event
	gridhis.attachEvent("onHeaderClick", grid_onHeaderClick);
	
	//load history
	fmdf_wait(1);
	var args = {};
	doPostAsyncJson(fmd.fmdCtx + "/rest/fmd/queryHistory",
		{"formid" : fmdc.version.formid, 
		"versionid" : fmdc.version.versionid, 
		"args":JSON.stringify(args),
		"fromRow":1, "toRow":10, 
		"timezoneOffset":new Date().getTimezoneOffset(),
		"ordercolumns":JSON.stringify(gridhis._grid_ordercolumns)},
		function(ret) {
			fmdf_wait(0);
			if (!ret) {
				msgErr(fmd_i18n_msg_readfail);
			} else {
				fmdf_wait(1);
				gridhis.clearAll();
				gridhis.parse(ret, 'json');
				var rn = gridhis.getRowsNum();
				if (rn) {
					for (var i=0; i<rn; i++) {
						gridhis.cellByIndex(i, 7).setValue(
								'<img class="gridbtnimg" src="'+fmd.imagepath+
								'restore1.png"'+
								' onclick="designer.loadHistory(event,\''+gridhis.cellByIndex(i, 3).getValue()+'\')"/>'+fmd_i18n_b_restore1);
					}
				}
				fmdf_wait(0);
			}
		},
		function() {
			msgErr(fmd_i18n_msg_readfail);
			fmdf_wait(0);
		});
}

//load history
function fmdf_loadHistory(e, changeno) {
	fmdf_stopEvent(e);
	fmdf_wait(1);
	doPostAsyncJson(fmd.fmdCtx + "/rest/fmd/getHistory",
			{"formid" : fmdc.version.formid, 
			"versionid" : fmdc.version.versionid, 
			"changeno":changeno},
			function(ret) {
				if (!ret) {
					msgErr(fmd_i18n_msg_readfail);
					return;
				}
				fmdc.version.formdata = JSON.parse(ret.formdata);
				fmdf_cleanCanvas();
				fm_closeWindow('win_his');
				$.when(fmdf_loadSavedData()).done(function(){
					fmdf_wait(0);
					msg(fmd_i18n_msg_restored);
				});
			},
			function() {
				msgErr(fmd_i18n_msg_readfail);
				fmdf_wait(0);
				fm_closeWindow('win_his');
			});
	//setTimeout("fm_closeWindow('win_his');msg(fmd_i18n_msg_restored);", 500);
}

//set view of advanced
function fmdf_setAdvancedView(s, init) {
	init && fmdc.fmd_tb.setItemState('fmd_mcb_showadvanced', s);
	if (s) {
		//fmd.tabbar.tabs('fmdtab_permission').show();
		fmd.tabbar.tabs('fmdtab_ref').show();
		fmd.tabbar.tabs('fmdtab_script').show();
		fmdc.fmd_tb.setItemImage('fmd_mcb_showadvanced', "showadvanced.png");
		fmdc.fmd_tb.setItemText('fmd_mcb_showadvanced', fmd_i18n_b_showadvanced);
	} else {
		//fmd.tabbar.tabs('fmdtab_permission').hide();
		var atabId = fmd.tabbar.getActiveTab();
		if (atabId=='fmdtab_ref' || atabId=='fmdtab_script') {
			fmd.tabbar.tabs('fmdtab_basic').setActive();
		}
		fmd.tabbar.tabs('fmdtab_ref').hide();
		fmd.tabbar.tabs('fmdtab_script').hide();
		fmdc.fmd_tb.setItemImage('fmd_mcb_showadvanced', "showadvanced_dis.png");
		fmdc.fmd_tb.setItemText('fmd_mcb_showadvanced', fmd_i18n_b_showadvanced_dis);
	}
}

//copy from other form
function fmdf_importfrom() {
	
	var activetab = fmdc.tabs.find(".ui-tabs-active");
	if (!activetab.length) {
		msg(fmd_i18n_msg_plscreatetab);
		return;
	}
	
	/*var sel = fmdf_getSelected();
	if (sel && sel.length
			&& (sel.hasClass('fmdtd')
				|| sel.hasClass('fmcontainer_block')
				|| sel.hasClass('fmdcanvas_tabnavli')
					)) {
		//continue
	} else {
		msg(fmd_i18n_msg_plsseltargetcontainer);
		return;
	}*/
	var currentBlockId = null;
	var sel = fmdf_getSelected();
	if (sel && sel.length) {
		currentBlockId = sel.hasClass('fmcontainer_block') ? sel.attr('id') : null;
		if (sel.hasClass('fmdtd') || sel.hasClass('fmddropped')) {
			currentBlockId = sel.parents('.fmcontainer_block:first').attr('id');
		}
	}
	
	var w1 = fm_createCenterWindow('wid_selectForm', fmd_i18n_prop_selectformversion, 800, 600);
	var lo = w1.attachLayout("2E");
	lo.cells('a').hideHeader();
	lo.cells('b').hideHeader();
	lo.cells('b').setHeight(50);
	
	var str2 = [
		   		{ type:"block" , name:"form_block_1", offsetLeft:(dhx_skin=="dhx_web"?"333":"343"), offsetTop:"0", list:[
		   		{ type:"button" , name:"fb_ok", value:fmd_i18n_b_next, inputTop:0  }
		   		]  }
		   	];
	var fm2 = lo.cells('b').attachForm(str2);
	var lo1 = lo.cells('a').attachLayout("2U");
	lo1.cells('a').setText(fmd_i18n_prop_form);
	lo1.cells('b').setText(fmd_i18n_prop_version);
	lo1.setAutoSize("a;b", "a;b");
	lo1.cells('a').setWidth(400);
	var fmg = {};
	fmg.rest_queryf = fmd.fmdCtx + '/rest/fmd/queryForm';
	fmg.rest_queryv = fmd.fmdCtx + '/rest/fmd/queryVersion';
	
	utp_initFormgrid();
	utp_initVersiongrid();
	
	fm2.attachEvent("onButtonClick", function(btid) {
		if (btid=='fb_ok') {
			var rid = fmg.vergrid.getSelectedRowId();
			if (!rid) {
				msg(fmd_i18n_msg_plsselformver);
				return;
			}
			utp_returnBindingForm(rid);
		}
	});
	
	//查询
	utp_toPagef(1, 10);
	
	//grid for form layout
	function utp_initFormgrid() {
		fmg.stb = lo1.cells('a').attachStatusBar();
		fmg.stb.setText("<div id='id_paging_selform_stb1'></div>");
		
		fmg.formgrid = lo1.cells('a').attachGrid();
		fmg.formgrid.setIconsPath(dhtmlx.image_path);
		fmg.formgrid.setHeader([fmd_i18n_l_no,"FORMID",fmd_i18n_prop_form_type,fmd_i18n_prop_form_name,fmd_i18n_prop_form_desc,fmd_i18n_prop_form_creator,fmd_i18n_prop_form_creatorname,"OP"],null,["text-align:center;","text-align:center;","text-align:center","text-align:center;","text-align:center;","text-align:center;","text-align:center;","text-align:center;"]);
		fmg.formgrid.attachHeader("#rspan,&nbsp;,#rspan,<input id='sr_formname' type='text' style='width:90%'/>,<input id='sr_formdesc' type='text' style='width:90%'/>,#rspan,#rspan,#rspan");
		fmg.formgrid.setInitWidths("40,200,80,150,250,60,80,100");
		fmg.formgrid.setColumnIds("ROW_NO,FORMID,FORMTYPE,FORMNAME,FORMDESC,CREATOR,CREATORNAME,OP");
		fmg.formgrid.setColTypes("ro,ro,pairro,ro,ro,ro,ro,ro");
		fmg.formgrid.setColSorting("na,str,str,str,str,str,str,str");
		fmg.formgrid.setColumnsVisibility("false,true,true,false,false,true,false,true");
		fmg.formgrid.setColAlign("center,left,center,left,left,left,center,left");
		fmg.formgrid.setEditable(false);
		fmg.formgrid.setLang(fmd.lang);
		//default ordering
		fmg.formgrid._grid_ordercolumns = [{"CREATETIME":"DESC"}];
		
		//paging
		fmg.formgrid.setPagingWTMode(true,true,true,[10,20,50,100]);
		fmg.formgrid.enablePaging(true,10,5,'id_paging_selform_stb1');
		fmg.formgrid.setPagingSkin("toolbar", dhx_skin);
		
		fmg.formgrid.init();
		
		fmg.formgrid.attachEvent("onPageChanged", function(ind,fInd,lInd){
			utp_toPagef(fInd+1, lInd);
		});
		
		fmg.formgrid.attachEvent("onSelectStateChanged", function(grId){
			utp_toPagev(1, 10);
		});
		
		//header click event
		fmg.formgrid.attachEvent("onHeaderClick", grid_onHeaderClick);
		
		//bind searcher event
		//disable onclick order by function for this header
		var tdsr_formname = $("#sr_formname").parents('td:first');
		var tdsr_formdesc = $("#sr_formdesc").parents('td:first');
		var tdsr_formdescnext = $("#sr_formdesc").parents('td:first').next();
		tdsr_formname.bind('click',utp_stopEvent);
		tdsr_formdesc.bind('click',utp_stopEvent);
		tdsr_formdescnext.bind('click',utp_stopEvent);
		tdsr_formname.bind('mouseover',utp_stopEvent);
		tdsr_formdesc.bind('mouseover',utp_stopEvent);
		tdsr_formdescnext.bind('mouseover',utp_stopEvent);
		$("#sr_formname").bind('keypress', utp_enterQueryf);
		$("#sr_formdesc").bind('keypress', utp_enterQueryf);
	}

	//grid for version layout
	function utp_initVersiongrid() {
		fmg.vtb = lo1.cells('b').attachStatusBar();
		fmg.vtb.setText("<div id='id_paging_selform_stb2'></div>");
		
		fmg.vergrid = lo1.cells('b').attachGrid();
		fmg.vergrid.setIconsPath(dhtmlx.image_path);
		fmg.vergrid.setHeader([fmd_i18n_l_no,"VERSIONID",fmd_i18n_prop_form_name,fmd_i18n_prop_form_desc,fmd_i18n_prop_form_updatetime,fmd_i18n_prop_form_changeuserid,fmd_i18n_prop_form_changeusername,fmd_i18n_prop_form_checkoutby,fmd_i18n_prop_form_checkoutbyname,fmd_i18n_prop_form_creator,fmd_i18n_prop_form_creatorname,fmd_i18n_prop_form_status,"OP"],
				null,
				["text-align:center;","text-align:left;","text-align:left","text-align:left","text-align:center;","text-align:center;","text-align:center;","text-align:center;","text-align:center;","text-align:center;","text-align:center;","text-align:center;","text-align:center;"]);
		fmg.vergrid.attachHeader("#rspan,#rspan,<input id='sr_versionname' type='text' style='width:90%'/>,<input id='sr_versiondesc' type='text' style='width:90%'/>,#rspan,#rspan,#rspan,#rspan,#rspan,#rspan,#rspan,#rspan,#rspan");
		fmg.vergrid.setInitWidths("40,100,150,250,120,80,80,80,80,80,80,80,100");
		fmg.vergrid.setColumnIds("ROW_NO,VERSIONID,VERSIONNAME,VERSIONDESC,UPDATETIME,CHANGEUSERID,CHANGEUSERNAME,CHECKOUTBY,CHECKOUTBYNAME,CREATOR,CREATORNAME,STATUS,OP");
		fmg.vergrid.setColTypes("ro,ro,ro,ro,ro,ro,ro,ro,ro,ro,ro,pairro,ro");
		fmg.vergrid.setColSorting("na,str,str,str,str,str,str,str,str,str,str,str,str");
		fmg.vergrid.setColumnsVisibility("false,true,false,false,false,true,false,true,false,true,false,true,true");
		fmg.vergrid.setColAlign("center,left,left,left,center,center,center,center,center,center,center,center,center");
		fmg.vergrid.setEditable(false);
		fmg.vergrid.setLang(fmd.lang);
		fmg.vergrid.init();
		
		//default order by
		//fmg.vergrid._grid_ordercolumns = [{"CREATETIME":"DESC"}];
		
		//paging
		fmg.vergrid.setPagingWTMode(true,true,true,[10,20,50,100]);
		fmg.vergrid.enablePaging(true,10,5,'id_paging_selform_stb2');
		fmg.vergrid.setPagingSkin("toolbar", dhx_skin);
		
		fmg.vergrid.attachEvent("onPageChanged", function(ind,fInd,lInd){
			utp_toPagev(fInd+1, lInd);
		});
		
		//header click event
		fmg.vergrid.attachEvent("onHeaderClick", grid_onHeaderClick);
		
		fmg.vergrid.attachEvent("onRowDblClicked", function(grId, gcInd){
			utp_returnBindingForm(grId);
		});
		
		//bind searcher event
		//disable onclick order by function for this header
		var trsr_versionname = $("#sr_versionname").parents('tr:first');
		trsr_versionname.find('td').bind('click',utp_stopEvent);
		trsr_versionname.find('td').bind('mouseover',utp_stopEvent);
		$("#sr_versionname").bind('keypress', utp_enterQueryv);
		$("#sr_versiondesc").bind('keypress', utp_enterQueryv);
	}
	
	//query form
	function utp_toPagef(fromRow, toRow){
		lo1.cells('a').progressOn();
		var p = {"form":{"formtype":"PROCESS"}, "fromRow":fromRow, "toRow":toRow, "timezoneOffset":new Date().getTimezoneOffset(),
				"ordercolumns":JSON.stringify(fmg.formgrid._grid_ordercolumns)};
		if (fmg.fquery_formname) {
			p.form.formname = fmg.fquery_formname;
		}
		if (fmg.fquery_formdesc) {
			p.form.formdesc = fmg.fquery_formdesc;
		}
		p.form = JSON.stringify(p.form);
		doPostAsyncJson(fmg.rest_queryf, p,
			function(ret){
				if (!ret) {
					lo1.cells('a').progressOff();
					msgErr(fmd_i18n_msg_readfail);
					return;
				}
				fmg.formgrid.clearAllInPaging();
				fmg.formgrid.parse(ret, "json");
				fmg.vergrid.clearAllInPaging();
				lo1.cells('a').progressOff();
			},
			function(){
				lo1.cells('a').progressOff();
				msgErr(fmd_i18n_msg_readfail);
			});
	}

	//call query form
	function utp_enterQueryf(e) {
		if (e.keyCode==13) {
			fmg.fquery_formname = $.trim($("#sr_formname").val());
			fmg.fquery_formdesc = $.trim($("#sr_formdesc").val());
			utp_toPagef(1, 10);
		}
	}

	//query version
	function utp_toPagev(fromRow, toRow){
		lo1.cells('b').progressOn();
		var p = {"args":{}, "fromRow":fromRow, "toRow":toRow, "timezoneOffset":new Date().getTimezoneOffset(),
				"ordercolumns":JSON.stringify(fmg.vergrid._grid_ordercolumns)};
		p.args.formid = fmg.formgrid.cells(fmg.formgrid.getSelectedRowId(), fmg.formgrid.getColIndexById("FORMID")).getValue();
		if (fmg.vquery_versionname) {
			p.args.versionname = fmg.vquery_versionname;
		}
		if (fmg.vquery_versiondesc) {
			p.args.versiondesc = fmg.vquery_versiondesc;
		}
		p.args = JSON.stringify(p.args);
		doPostAsyncJson(fmg.rest_queryv, p,
			function(ret){
				if (!ret) {
					lo1.cells('b').progressOff();
					msgErr(fmd_i18n_msg_readfail);
					return;
				}
				fmg.vergrid.clearAllInPaging();
				fmg.vergrid.parse(ret, "json");
				//hide current version display
				var sr = fmg.vergrid.findCell("0",fmg.vergrid.getColIndexById("VERSIONID"),true);
				if (sr && sr.length && sr[0].length) {
					fmg.vergrid.cells(sr[0][0], fmg.vergrid.getColIndexById("VERSIONNAME")).setValue(fmd_i18n_prop_version_current);
				}
				lo1.cells('b').progressOff();
			},
			function(){
				lo1.cells('b').progressOff();
				msgErr(fmd_i18n_msg_readfail);
			});
	}

	//call query version
	function utp_enterQueryv(e) {
		if (e.keyCode==13) {
			fmg.vquery_versionname = $.trim($("#sr_versionname").val());
			fmg.vquery_versiondesc = $.trim($("#sr_versiondesc").val());
			utp_toPagev(1, 10);
		}
	}

	//stop event propagation
	function utp_stopEvent(e){
		if (e && e.stopPropagation!=undefined) {
			e.stopPropagation();
		} else if (window.event){
			window.event.cancelBubble = true;
		}
		return false;
	}
	
	//返回
	function utp_returnBindingForm(rid) {
		var frid = fmg.formgrid.getSelectedRowId();
		var formid = fmg.formgrid.cells(frid, fmg.formgrid.getColIndexById("FORMID")).getValue();
		var formname = fmg.formgrid.cells(frid, fmg.formgrid.getColIndexById("FORMNAME")).getValue();
		var versionid = fmg.vergrid.cells(rid, fmg.vergrid.getColIndexById("VERSIONID")).getValue();
		var versionname= fmg.vergrid.cells(rid, fmg.vergrid.getColIndexById("VERSIONNAME")).getValue();
		if (formid==fmdc.version.formid && versionid==fmdc.version.versionid) {
			msg(fmd_i18n_msg_selectediscurver);return;
		}
		lo.cells('a').progressOn();
		doPostAsyncJson(fmd.fmdCtx + "/rest/fmd/getVersion",
				{"formid" : formid, "versionid" : versionid},
				function(ret) {
					lo.cells('a').progressOff();
					if (ret) {
						w1.close();
						utp_showImportBox(ret.version.formdata, formname+' - '+versionname);
					} else {
						msgErr(fmd_i18n_msg_readfail);
					}
				}, 
				function() {
					lo.cells('a').progressOff();
					msgErr(fmd_i18n_msg_readfail);
				});
	}
	
	function utp_showImportBox(formdata, roottext) {
		var w2 = fm_createCenterWindow('wid_selectFormElem', fmd_i18n_prop_selectformelem, 600, 600);
		var low2 = w2.attachLayout("2E");
		low2.cells('a').hideHeader();
		low2.cells('b').hideHeader();
		low2.cells('b').setHeight(50);
		
		var str3 = [
			   		{ type:"block" , name:"form_block_1", offsetLeft:(dhx_skin=="dhx_web"?"230":"240"), offsetTop:"0", list:[
			   		{ type:"button" , name:"fb_ok", value:fmd_i18n_b_ok, inputTop:0  }
			   		]  }
			   	];
		var fm3 = low2.cells('b').attachForm(str3);
		
		var tb_tree = low2.cells('a').attachToolbar();
		tb_tree.setIconsPath(fmdc.imagepath);
		tb_tree.loadStruct('<toolbar><item type="button" id="expandAll" text="'+fmd_i18n_prop_expand+'" img="expand1.png"/><item type="button" id="foldAll" text="'+fmd_i18n_prop_collapse+'" img="fold1.png"/><item type="buttonInput" id="formElemImportTreeFinder" width="100" title="'+fmd_i18n_prop_tip_quickfind+'"/><item type="button" id="formElemImportTreeFinderBtn" img="find.gif"/></toolbar>', function() {});
		tb_tree.addButtonTwoState('imp2selectedblock', 0, fmd_i18n_prop_impselectedblock1st, 'item_chk0.gif', 'item_chk0.gif');
//		tb_tree.addSpacer("foldAll");
		tb_tree.addSpacer("imp2selectedblock");
		if (!currentBlockId) {
			tb_tree.hideItem("imp2selectedblock");
		}
		
		//流程定义树
		var mytree1 = low2.cells('a').attachTree();
		mytree1.setIconsPath(dhtmlx.image_path+"dhxtree_"+dhx_skin.substr(4)+"/");
		mytree1.setImagesPath(dhtmlx.image_path+"dhxtree_"+dhx_skin.substr(4)+"/");
		mytree1.enableCheckBoxes(true);
		mytree1.enableThreeStateCheckboxes(true);
		//mytree1.enableSmartCheckboxes(1);
		
		mytree1.attachEvent("onClick", function(_id, object){
			mytree1.selectItem(_id);
	    });
		mytree1.attachEvent("onRightClick", function(_id, object){
			mytree1.selectItem(_id);
	    });
		
		tb_tree.attachEvent("onStateChange", function(tbid, state){
			if ('imp2selectedblock'==tbid) {
				tb_tree.setItemImage('imp2selectedblock', state ? "item_chk1.gif" : "item_chk0.gif");
			}
		});
		//tree buttons
	    tb_tree.attachEvent('onClick', function(btid){
	    	if (btid == "foldAll") {
	        	mytree1.closeAllItems("0");
	        } else if (btid == "expandAll"){
	        	mytree1.openAllItems("0");
	        } else if (btid == "formElemImportTreeFinderBtn"){
	        	var txt = tb_tree.getValue('formElemImportTreeFinder');
	    		txt && mytree1.findItem(txt, 0);
	        };
	    });
	    tb_tree.attachEvent('onEnter', function(btid){
	    	if (btid == "formElemImportTreeFinder") {
	    		var txt = tb_tree.getValue(btid);
	    		txt && mytree1.findItem(txt, 0);
	        }
	    });
	    
	    fm3.attachEvent("onButtonClick", function(btid) {
			if (btid=='fb_ok') {
				var cb = mytree1.getAllChecked();
				if (!cb) {
					msg(fmd_i18n_msg_plsselmorethan1elem);return;
				}
				cb = cb.split(',').filter(function(id){
					return !!elemcontrols[id];
				});
				if (!cb.length) {
					msg(fmd_i18n_msg_plsselmorethan1elem);return;
				}
				doElemImport(cb, tb_tree.getItemState('imp2selectedblock'));
				w2.close();
			}
		});
	    
	    //load treedata
		var propconf = formdata.propconf;
		var rowcount = 1;
		var elemtypes = {};
		var elemcontrols = {};
		var elemfmdcols = {};
		var elemmodels = {};
		//
		function find_databinding(conf) {
			if (conf.databinding) {
				elemmodels[conf.databinding.split('.')[0]]=true;
				return " &gt;&gt; "+conf.databinding;
			}
			if (conf["databinding-realvalue"]) {
				elemmodels[conf["databinding-realvalue"].split('.')[0]]=true;
				elemmodels[conf["databinding-displayvalue"].split('.')[0]]=true;
				return " &gt;&gt; "+conf["databinding-realvalue"]+","+conf["databinding-displayvalue"];
			}
			if (conf.model) {
				elemmodels[conf.model] = true;
				return " &gt;&gt; "+conf.model;
			}
			return "";
		}
		//pathinfo - 记录组件所在路径信息[id1,id2]
		function addChildrenForTreeRoot(targetRoot, sourceRoot, parentpathinfo) {
			if (sourceRoot.tabs && sourceRoot.tabs.length) {
				for (var i=0;i<sourceRoot.tabs.length;i++) {
					var pathinfo = parentpathinfo ? parentpathinfo.slice() : [];
					var id = sourceRoot.tabs[i].id;
					pathinfo.push(id);
					var conf = propconf[id];
					var newnode = {id:id, 
							text:fmd_i18n_l_fmcontainer_tab+': '+conf["i18nname-"+fmd.lang]};
					if (sourceRoot.tabs[i].type=='tab') {
						newnode.im0='newtab.gif',newnode.im1='newtab.gif',newnode.im2='newtab.gif';
						addChildrenForTreeRoot(newnode, sourceRoot.tabs[i], pathinfo);
					}
					targetRoot.item = targetRoot.item || [];
					targetRoot.item.push(newnode);
					elemtypes[id] = sourceRoot.tabs[i].type;
				}
			} else if (sourceRoot.items && sourceRoot.items.length) {
				for (var i=0;i<sourceRoot.items.length;i++) {
					var pathinfo = parentpathinfo ? parentpathinfo.slice() : [];
					var id=sourceRoot.items[i].id;
					var ntype = sourceRoot.items[i].type;
					if (id==undefined) id = 'div12row_'+rowcount++;
					var newnode = {'id':id};
					if (ntype=='div12block') {
						var text = propconf[id]["i18nname-"+fmd.lang] || '';
						text += (!text ? fmd_i18n_untitled : '')+' ('+id+')';
						newnode.text = fmd_i18n_l_fmcontainer_block+': '+text;
						newnode.im0='newcont_div12.png',newnode.im1='newcont_div12.png',newnode.im2='newcont_div12.png';
						pathinfo.push(id);
						addChildrenForTreeRoot(newnode, sourceRoot.items[i], pathinfo);
					} else if (ntype=='div12row') {
						newnode.text = fmd_i18n_prop_form_row;
						newnode.im0='newrow.gif',newnode.im1='newrow.gif',newnode.im2='newrow.gif';
						pathinfo.push(id);
						addChildrenForTreeRoot(newnode, sourceRoot.items[i], pathinfo);
					} else if (ntype=='div12cell') {
						newnode.text = fmd_i18n_l_fmcontainer_cell+' ('+id+')';
						newnode.im0='newcolafter.gif',newnode.im1='newcolafter.gif',newnode.im2='newcolafter.gif';
						pathinfo.push(id);
						elemfmdcols[id] = sourceRoot.items[i].fmdcols;
						addChildrenForTreeRoot(newnode, sourceRoot.items[i], pathinfo);
					} else if ('control'==sourceRoot.items[i].compType) {//element
						var conf = propconf[id];
						var text = conf["i18nname-"+fmd.lang] || '';
						text += (!text ? fmd_i18n_untitled : '')+' ('+id+')';
						text += find_databinding(conf);
						newnode.text = fmdmeta_prop.control[ntype].i18ntype + ': '+text;
						newnode.tooltip = fmdmeta_prop.control[ntype].i18ntype;
						newnode.im0='elem_'+ntype+'.png',newnode.im1='elem_'+ntype+'.png',newnode.im2='elem_'+ntype+'.png';
						pathinfo.push(id);
						elemcontrols[id] = pathinfo;
					}
					targetRoot.item = targetRoot.item || [];
					targetRoot.item.push(newnode);
					elemtypes[id] = ntype;
				}
			}
		}
		//load data
		var treeData = {"id":"0","item":[{"id":"root","text":roottext, "im0":"canvas.png", "im1":"canvas.png", "im2":"canvas.png"}]};
		var treeRoot = treeData.item[0];
		addChildrenForTreeRoot(treeRoot, formdata.formconf);
		mytree1.loadJSONObject(treeData, function() {
			mytree1.showItemCheckbox('root', false);
			var subs = mytree1.getSubItems('root');
			if (subs) {
				var subs1 = subs.split(',');
				for (var i in subs1) {
					mytree1.showItemCheckbox(subs1[i], false);
				}
			}
		});
		mytree1.openAllItems("0");
		$(tb_tree.getInput('formElemImportTreeFinder')).focus();
		
		//return data and do import
		function doElemImport(ids, imp2selectedblock) {
			while (ids.length>0) {
				var elid = ids.shift();
				var path = elemcontrols[elid];
				//console.log(path);
				for (var i=0;i<path.length;i++) {
					var pid = path[i];
					var elemtype = elemtypes[pid];
					var pconf = propconf[pid];
					var newid, curblockid, curtr, curtd, curtrid, curtdid;
					if (pconf) {
						newid = fmdf_uiid();
						var strpconf = JSON.stringify(pconf).replace(/ui-id-\d+/g, function(a){
								return pid==a ? newid : a;
							});
						pconf = JSON.parse(strpconf);
						pconf.id = newid;
						fmdc.version.formdata.propconf[newid] = pconf;
					}
					
					switch(elemtype) {
						case 'tab':
							
							break;
						case 'div12block':
							if (imp2selectedblock) {
								fmdf_selectById(currentBlockId);
							} else if (curblockid!=pid) {
								curblockid = pid;
								fmdf_fmcontainer_block_addcontainer(pconf.pattern, newid);
								fmdpf_apply();
							}
							break;
						case 'div12row':
							if (curtrid!=pid) {
								curtrid = pid;
								curtr = fmdf_fmcontainer_block_appendtr();
							}
							break;
						case 'div12cell':
							if (curtdid != pid) {
								curtdid = pid;
								curtd = fmdf_fmcontainer_block_appendtd(curtr, newid, null, elemfmdcols[pid]);
							}
							break;
						default:
							var multielement = !!fmdmeta_prop.control[elemtype].multielement;
							curtd.append( '<div class="fmddropped fmdelement_'+elemtype+'" onclick="designer.onselect(event,this);"'+
									(multielement ? ' style="float:left;margin:0.6em 0.4em 0.6em 0.4em;"' : '') + '>'+
									eval("fmdmeta_prop.control[elemtype].innerhtml_dropped" + (typeof(fmdmeta_prop.control[elemtype].innerhtml_dropped)=="function" ? "()":""))+
									'</div>' );
							var dropped = curtd.children('.fmddropped:last');
							fmd.isEditor && dropped.draggable(fmdc.draggable_args_nohelper);
							dropped.attr("id", newid);
							//select the new component
							fmdf_select(dropped);
							fmdpf_apply();
					}
				}
			}
			//import models
			for (var m in elemmodels) {
				fmdc.version.formdata.models[m] = formdata.models[m];
			}
			fmdc.unsavedchange = true;
		}
	}
	
}

//init for creating form
function fmdf_initCreate() {
	fmdf_resetVars();
	fmdf_cleanCanvas();
}

//init for updating form
function fmdf_initUpdate(formid) {
	//reset
	fmdf_resetVars();
	fmdf_cleanCanvas();
	//load form data
}

//get form configure
function fmdf_getFormConf() {
	var rtn = {"tabs":[]};
	//iterate tab
	$(".fmdcanvas .fmdcanvas_tabnav .fmdcanvas_tabnavli").each(function(idxtab, elemtab) {
		//validate
		fmdf_select($(elemtab));
		if (!fmdpf_apply()) {
			return null;
		}
		var tabid = $(elemtab).attr("id");
		var tabtitle = $(elemtab).find('a').html();
		var tabtype = $(elemtab).attr("tabtype");
		//alert("tabid="+tabid + " bodyid="+"#fmcontainer_tabbody_"+tabid.substr(16));
		var tabbody = $("#fmcontainer_tabbody_"+tabid.substr(16));
		//iterate block
		var itemsblock = [];
		tabbody.find(".fmcontainer_block").each(function(idxblock, elemblock) {
			//validate
			fmdf_select($(elemblock));
			if (!fmdpf_apply()) {
				return false;
			}
			//max spans
			var maxspans = fmdf_getMaxCols($(elemblock).find("table tbody"));
			//iterate row
			var itemsrow = [];
			var fmdpattern = $(elemblock).attr("fmdpattern");
			//if (fmdpattern=='table') {//user html table pattern
				
				$(elemblock).find(".fmdtr").each(function(idxrow, elemrow) {
					//iterate cell
					var itemscell = [];
					$(elemrow).find(".fmdtd").each(function(idxcell, elemcell) {
						//validate
						fmdf_select($(elemcell));
						if (!fmdpf_apply()) {
							return false;
						}
						//iterate elements
						var itemselem = [];
						$(elemcell).children(".fmddropped").each(function(idxelem, elemelem) {
							//validate
							fmdf_select($(elemelem));
							if (!fmdpf_apply()) {
								return false;
							}
							var elemtype = fmdf_getElemType($(elemelem));
							var elemprop = {"id" : $(elemelem).attr("id"), "compType" : "control", "type" : elemtype};
							if ('table'==fmdpattern) {
								elemprop.maxspans = maxspans;
							} else if ('div12'==fmdpattern) {
								elemprop.fmdcols = $(elemcell).attr("fmdcols");
							}
							itemselem.push(elemprop);
						});
						//break cell each if validation failed
						if (!MyUtilJs.isEmpty(fmdc.proptemp.vfailure)) return false;
						var cellprop = {"id" : $(elemcell).attr("id"), "compType" : "layout", "items" : itemselem};
						if ('table'==fmdpattern) {
							cellprop.type = "cell";
							cellprop.maxspans = maxspans;
							cellprop.colspan = $(elemcell).attr("colspan") || "1";
							cellprop.rowspan = $(elemcell).attr("rowspan") || "1";
						} else if ('div12'==fmdpattern) {
							cellprop.type = "div12cell";
							cellprop.fmdcols = $(elemcell).attr("fmdcols");
						}
						itemscell.push(cellprop);
					});
					//break row each if validation failed
					if (!MyUtilJs.isEmpty(fmdc.proptemp.vfailure)) return false;
					itemsrow.push({"id" : $(elemrow).attr("id"), "compType" : "layout", "type" : (fmdpattern=='div12'?'div12row':'tr'), "items" : itemscell});
				});
				//break block each if validation failed
				if (!MyUtilJs.isEmpty(fmdc.proptemp.vfailure)) return false;
				
			/*} else if ($(elemblock).attr("fmdpattern")=='div12') {//use html div(12max in one row) pattern
				
			}*/
			//break tab each if validation failed
			if (!MyUtilJs.isEmpty(fmdc.proptemp.vfailure)) return false;
			itemsblock.push({"id" : $(elemblock).attr("id"), "compType" : "layout", "type" : (fmdpattern=='div12'?'div12block':'block'), "pattern" : $(elemblock).attr("fmdpattern"), "items" : itemsrow, "maxspans" : maxspans});
		});
		//alert("pushing="+JSON.stringify({"id" : tabid, "compType" : "layout", "type" : "tab", "items" : itemsblock}));
		rtn.tabs.push({"id" : tabid, "compType" : "layout", "type" : "tab", 
			"tabtype" : tabtype, "title" : tabtitle, "items" : itemsblock});
	});
	
	//判断是否有验证错误
	if (!MyUtilJs.isEmpty(fmdc.proptemp.vfailure)) {//return null if validation failed
		fmd.tabbar.cells('fmdtab_canvas').setActive();
		return null;
	}
	
	//检查脚本错误
	if (fmdc.editor_bodyscript && fmdc.editor_bodyscript.session) {
		var annos = fmdc.editor_bodyscript.session.getAnnotations();
		for (var i in annos) {
			if (annos[i].type=='error') {
				msg(fmd_i18n_b_showadvanced+"-"+fmd_i18n_l_bodyscript+": "+fmd_i18n_msg_hasvalidationerr);
				fmd.tabbar.cells('fmdtab_script').setActive();
				return false;
			}
		}
	}
	if (fmdc.editor_readyscript && fmdc.editor_readyscript.session) {
		var annos = fmdc.editor_readyscript.session.getAnnotations();
		for (var i in annos) {
			if (annos[i].type=='error') {
				msg(fmd_i18n_b_showadvanced+"-"+fmd_i18n_l_readyscript+": "+fmd_i18n_msg_hasvalidationerr);
				fmd.tabbar.cells('fmdtab_script').setActive();
				return false;
			}
		}
	}
	if (fmdc.editor_datareadyscript && fmdc.editor_datareadyscript.session) {
		var annos = fmdc.editor_datareadyscript.session.getAnnotations();
		for (var i in annos) {
			if (annos[i].type=='error') {
				msg(fmd_i18n_b_showadvanced+"-"+fmd_i18n_l_datareadyscript+": "+fmd_i18n_msg_hasvalidationerr);
				fmd.tabbar.cells('fmdtab_script').setActive();
				return false;
			}
		}
	}
	
	return rtn;
}

//load form config
function fmdf_loadFormConf() {
	fmd.tabbar.cells('fmdtab_canvas').progressOn();
	//set form
	fmdc.form_basic.setItemValue('fi_basic_type', fmd_i18n.enu.fmtype[fmdc.form.formtype]);
	fmdc.form_basic.setItemValue('fi_basic_name', fmdc.form.formname);
	fmdc.form_basic.setItemValue('fi_basic_desc', fmdc.form.formdesc);
	if (fmdc.version) {
		if (fmdc.version.versionid=='0') {//current version
			fmdc.form_basic.setItemValue('fi_basic_vname', fmd_i18n_curver);
			fmdc.form_basic.disableItem('fi_basic_vname');
		} else {
			fmdc.form_basic.setItemValue('fi_basic_vname', fmdc.version.versionname);
		}
		fmdc.form_basic.setItemValue('fi_basic_vdesc', fmdc.version.versiondesc);
		fmdc.form_basic.showItem('fieldset_versionbasic');
	}
	//set readonly if not editor
	//!fmd.isEditor && $(fmdc.form_basic.getInput('fi_basic_type')).parents('.dhxform_base:first').find('input').attr("disabled", "disabled");
	if (!fmd.isEditor) {
		fmdc.form_basic.forEachItem(function(id){
			fmdc.form_basic.disableItem(id);
		});
	}
	
	//set canvas
	//add tab
	if (!fmdc.version.formdata.formconf.tabs || !fmdc.version.formdata.formconf.tabs.length) return;
	for (var i in fmdc.version.formdata.formconf.tabs) {
		fmdf_addtab(fmdc.version.formdata.formconf.tabs[i].title, fmdc.version.formdata.formconf.tabs[i].tabtype, fmdc.version.formdata.formconf.tabs[i].id);
		fmdpf_apply();
		//add block
		if (!fmdc.version.formdata.formconf.tabs[i].items || !fmdc.version.formdata.formconf.tabs[i].items.length) continue;
		for (var j in fmdc.version.formdata.formconf.tabs[i].items) {
			var fmdpattern = fmdc.version.formdata.formconf.tabs[i].items[j].pattern;
			fmdf_fmcontainer_block_addcontainer(fmdpattern, fmdc.version.formdata.formconf.tabs[i].items[j].id);
			fmdpf_apply();
			//alert(fmdc.version.formdata.formconf.tabs[i].items[j].pattern);
			//if (fmdpattern=='table') {//block in html table pattern
				//add tr
				if (!fmdc.version.formdata.formconf.tabs[i].items[j].items || !fmdc.version.formdata.formconf.tabs[i].items[j].items.length) continue;
				for (var k in fmdc.version.formdata.formconf.tabs[i].items[j].items) {
					var tr = fmdf_fmcontainer_block_appendtr();
					//add td
					if (!fmdc.version.formdata.formconf.tabs[i].items[j].items[k].items || !fmdc.version.formdata.formconf.tabs[i].items[j].items[k].items.length) continue;
					for (var l in fmdc.version.formdata.formconf.tabs[i].items[j].items[k].items) {
						var cell = fmdf_fmcontainer_block_appendtd(tr, fmdc.version.formdata.formconf.tabs[i].items[j].items[k].items[l].id, 
								fmdc.version.formdata.formconf.tabs[i].items[j].items[k].items[l].rowspan, fmdc.version.formdata.formconf.tabs[i].items[j].items[k].items[l].fmdcols);
						fmdpf_apply();
						//add element
						if (!fmdc.version.formdata.formconf.tabs[i].items[j].items[k].items[l].items || !fmdc.version.formdata.formconf.tabs[i].items[j].items[k].items[l].items.length) {
							cell.html(fmdc.tipp);
						} else {
							for (var m in fmdc.version.formdata.formconf.tabs[i].items[j].items[k].items[l].items) {
								var elemtype = fmdc.version.formdata.formconf.tabs[i].items[j].items[k].items[l].items[m].type;
								var multielement = !!fmdmeta_prop.control[elemtype].multielement;
								cell.append( '<div class="fmddropped fmdelement_'+elemtype+'" onclick="designer.onselect(event,this);"'+
										(multielement ? ' style="float:left;margin:0.6em 0.4em 0.6em 0.4em;"' : '') + '>'+
										eval("fmdmeta_prop.control[elemtype].innerhtml_dropped" + (typeof(fmdmeta_prop.control[elemtype].innerhtml_dropped)=="function" ? "()":""))+
										'</div>' );
								var dropped = cell.children('.fmddropped:last');
								fmd.isEditor && dropped.draggable(fmdc.draggable_args_nohelper);
								dropped.attr("id", fmdc.version.formdata.formconf.tabs[i].items[j].items[k].items[l].items[m].id);
								//select the new component
								fmdf_select(dropped);
								fmdpf_apply();
							}
						}
					}
					if ('div12'==fmdpattern) {
						fmdf_refreshCellHeightDiv12(tr);
					}
				}
				
			//} else if (fmdc.version.formdata.formconf.tabs[i].items[j].pattern=='div12') {//block in html div pattern
				
			//}
		}
	}
	fmd.tabbar.cells('fmdtab_canvas').progressOff();
}

//get data for save
function fmdf_getDataForSave() {
	var formconf = fmdf_getFormConf();
	if (!formconf) {
		return null;
	}
	var data = {};
	data.formconf = formconf;
	//only record properties for existing elements
	data.propconf = {};
	for (var i in fmdc.version.formdata.propconf) {
		$('#'+i).length && (data.propconf[i] = fmdc.version.formdata.propconf[i]);
	}
	//alert(JSON.stringify(fmdc.version.formdata));
	//canvas settings
	data.settings = {};
	//is in advanced view
	data.settings.advancedview = fmdc.advancedview;
	//default font size in px, the same as that in body css
	data.settings.fontsize = fmdc.fontsize;
	//default canvas width in em, the same as width in class fmdcanvas
	data.settings.canvas_size_widthem = fmdc.canvas_size_widthem;
	//auto hide elements prop
	data.settings.autohideprop = fmdc.autohideprop;
	//tab page index for adding tab id
	data.settings.tabpageidx = fmdc.tabpageidx;
	//fmcontainer index for adding container id
	data.settings.contidx = fmdc.contidx;
	//ui index for adding new ui
	data.settings.uiidx = fmdc.uiidx;
	//validation errors
	fmdc.version.formdata.validateErr = fmdc.validateErr || [];
	
	//models
	data.models = fmdc.models;
	
	//ref script
	data.refscript = fmdc.editor_refscript.getValue();
	//header script
	data.readyscript = fmdc.editor_readyscript.getValue();
	//body script editor
	data.bodyscript = fmdc.editor_bodyscript.getValue();
	//data ready script
	data.datareadyscript = fmdc.editor_datareadyscript.getValue();
	
	//prop settings
	//data.propconf;
	
	//alert("fmdf_getDataForSave="+JSON.stringify(data));
	return data;
}

function fmdf_loadSavedData() {
	fmdf_wait(1);
	
	var dtd = $.Deferred();//使本方法异步执行
	
	function loadSavedDataAsync() {
		var ts = new Date();
		fmd.isloading = true;
		//is in advanced view
		fmdc.advancedview = fmdc.version.formdata.settings.advancedview;
		//default font size in px, the same as that in body css
		fmdc.fontsize = fmdc.version.formdata.settings.fontsize;
		//default canvas width in em, the same as width in class fmdcanvas
		fmdc.canvas_size_widthem = fmdc.version.formdata.settings.canvas_size_widthem;
		//auto hide elements prop
		fmdc.autohideprop = fmdc.version.formdata.settings.autohideprop;
		//tab page index for adding tab id
		fmdc.tabpageidx = fmdc.version.formdata.settings.tabpageidx;
		//fmcontainer index for adding container id
		fmdc.contidx = fmdc.version.formdata.settings.contidx;
		//ui index for adding new ui
		fmdc.uiidx = fmdc.version.formdata.settings.uiidx;
		//validation errors
		fmdc.validateErr = fmdc.version.formdata.validateErr || [];
		
		//models
		fmdc.models = fmdc.version.formdata.models;
		fmdf_loadModelList(true);
		
		//-ref script
		fmdc.editor_refscript.setValue(fmdc.version.formdata.refscript);
		//fmdf_initRefScript(true);
		//-header script
		fmdc.editor_readyscript.setValue(fmdc.version.formdata.readyscript);
		//fmdf_initReadyScript(true);
		//-body script editor
		fmdc.editor_bodyscript.setValue(fmdc.version.formdata.bodyscript);
		//fmdf_initBodyScript(true);
		//-ondataready script editor
		fmdc.editor_datareadyscript.setValue(fmdc.version.formdata.datareadyscript);
		//fmdf_initDataReadyScript(true);
		
		//load existing form configure
		fmd.tabbar.cells('fmdtab_canvas').setActive();
		fmdf_loadFormConf();
		fmdf_setAdvancedView(fmdc.advancedview, true);
		
		fmd.tabbar.cells('fmdtab_basic').setActive();
		
		fmdc.unsavedchange = false;
		fmd.isloading = false;
		fmdf_wait(0);
		var te = new Date();
		console.debug("fmdf_loadSavedData ellapsed ============ "+(te.getTime() - ts.getTime())+" milliseconds.");
		
		dtd.resolve();
	}
	
	setTimeout(loadSavedDataAsync(), 1);//make it async
	return dtd.promise();
}

//save
function fmdf_save() {
	fmdf_wait(1);
	
	//check basic form
	var formname = fmdc.form_basic.getItemValue("fi_basic_name");
	if (!formname || !$.trim(formname)) {
		dhtmlx.message(fmd_i18n_msg_inputformname);
		fmd.tabbar.cells('fmdtab_basic').setActive();
		fmdf_wait(0);
		return;
	}
	//get version name and desc update
	if (!fmdc.form_basic.isItemHidden('fieldset_versionbasic')) {
		var vname = fmdc.form_basic.getItemValue('fi_basic_vname');
		if (!vname || !$.trim(vname)) {
			dhtmlx.message(fmd_i18n_msg_inputvname);
			fmd.tabbar.cells('fmdtab_basic').setActive();
			fmdf_wait(0);
			return;
		}
		var vdesc = fmdc.form_basic.getItemValue('fi_basic_vdesc');
	}
	
	if (!$(".fmdcanvas .fmdcanvas_tabnav .fmdcanvas_tabnavli").length) {
		dhtmlx.message(fmd_i18n_msg_notdesigned);
		fmd.tabbar.cells('fmdtab_canvas').setActive();
		fmdf_wait(0);
		return;
	}
	
	//construct validation info
	fmdc.validateErr = [];
	
	//apply current properties setting
	fmdf_getSelected() && fmdpf_apply();
	
	var formdesc = fmdc.form_basic.getItemValue("fi_basic_desc");
	
	var data = fmdf_getDataForSave();
	if (data) {
		var version = {};
		version.formdata = JSON.stringify(data);
		var form = {"formtype":fmdc.form.formtype, "formname":formname};
		if (fmdc.form.formid) {
			form.formid = fmdc.form.formid;
			version.formid = fmdc.form.formid;
			version.versionid = fmdc.version.versionid;
			if (fmdc.version.versionid!='0' && vname) {//version name and desc can be updated for saved form
				version.versionname = vname;
				version.versiondesc = vdesc;
			}
		}
		formdesc && (form.formdesc = formdesc);
		var param = {"form" : form, "version":version};
		doPostAsyncJson(fmd.fmdCtx + "/rest/fmd/save",
				{"param" : JSON.stringify(param)},
				function(ret) {
					if (ret) {
						//success
						fmdc.form.formid = ret.formid;
						fmdc.version.versionid = ret.versionid;
						fmdc.version.formdata = data;
						fmdc.unsavedchange = false;
						msg(fmd_i18n_msg_succ);
					}
					fmdf_wait(0);
				},
				function(){
					fmdf_wait(0);
					msgErr(fmd_i18n_msg_readfail);
				});
		
	} else {
		fmdf_wait(0);
	}
}

//preview
function fmd_preview(previewName, restName) {
	
	function dopreviewpage(skin1) {
        fmdf_wait(1);
        doPostAsyncJson(fmd.fmdCtx + "/rest/fmd/"+restName,
                {"formid":fmdc.form.formid,
                "versionid":fmdc.version.versionid,
                "skin":skin1//"bootstrap-blue"
                },
                function(ret){
                    if (ret && ret.success) {
                        msg(fmd_i18n_msg_succ);
                        //openWindowByUrl('preview', ctxpath + ret.relativePath);
                        openWindowByUrl('preview'+new Date().getTime(), ctxpath + '/view/platform/fmd/preview?s='+skin1+'&l='+fmd.lang+'&ft='+fmdc.form.formtype+'&ff='+
                            fmdc.form.formid+'-'+fmdc.version.versionid+'-'+fmd.lang+'-'+skin1+'.jsp');
                    } else {
                        msgErr(fmd_i18n_msg_readfail + (ret ? ret.err : ''));
                    }
                    fmdf_wait(0);
                },
                function() {
                    fmdf_wait(0);
                    msgErr(fmd_i18n_msg_readfail);
                });
	}
	
	if (fmd_i18n.options_skins && fmd_i18n.options_skins.length==1) {
		dopreviewpage(fmd_i18n.options_skins[0].value);return;
	}
	
	var win_preview = fm_createCenterWindow('win_'+previewName, eval("fmd_i18n_b_"+previewName), 300, 200);
    var previewfmjs = [
                    { type:"settings" , labelWidth:270, inputWidth:270, position:"absolute"  },
                    { type:"combo" , name:"fi_preview_skin", options:fmd_i18n.options_skins, label:fmd_i18n_t_skin, labelLeft:5, labelTop:5, inputLeft:5, inputTop:20, required:true, readonly:true},
                    { type:"button" , name:"fb_preview_ok", value:fmd_i18n_b_ok, width:70, inputLeft:20, inputTop:120  },
                    { type:"button" , name:"fb_preview_cancel", value:fmd_i18n_b_cancel, width:70, inputLeft:150, inputTop:120  }
                ];
    var fmpreview1 = win_preview.attachForm(previewfmjs);
    fmpreview1.attachEvent("onButtonClick", function(btid){
        if (btid=='fb_preview_ok') {
            if (!fmpreview1.validate()) {
                return;
            }
            var skin1 = fmpreview1.getItemValue("fi_preview_skin");
            
            fmpreview1.unload();
            win_preview.close();
            
            dopreviewpage(skin1);
            
        } else if (btid=='fb_preview_cancel') {
            fmpreview1.unload();
            win_preview.close();
        }
    });
	
}

//show progress layer
function fmdf_wait(show) {
	show ? fmd.body_layout.cells('a').progressOn() : fmd.body_layout.cells('a').progressOff();
}

//load modules
function fmdf_loadModules(modulepath, modules, deployVersion) {
	for (var i in modules) {
		loadModule(fmd.lang, modulepath, modules[i], deployVersion, fmdf_postModuleLoaded);
	}
}

//after module loaded
function fmdf_postModuleLoaded(module) {
	var el = module.split('.')[1];
	if (typeof(fmdmeta_prop.control[el].postLoaded)=='function') {
		fmdmeta_prop.control[el].postLoaded(el);
	}
}

//new id
function fmdf_uiid() {
	var newid = "ui-id-"+fmdc.uiidx;
	fmdc.uiidx++;
	return newid;
}

//stop event propagation
function fmdf_stopEvent(e){
	if (e && e.stopPropagation!=undefined) {
		e.stopPropagation();
	} else if (window.event){
		window.event.cancelBubble = true;
	}
	return false;
}

//===== runtime functions

//on fmcontainer_block title bar clicked and select fmcontainer_block
function fmf_fmcontainer_block_togglecontent(thisimg) {
	var table1 = $(thisimg).parents('.fmcontainer_block').find('.fmcontainer_block_content');
	table1.toggle("blind", {}, 300, function() {
		if (table1.is(":visible")) {
			thisimg.src=fmdc.imagepath+'/collapse.png';
		} else {
			thisimg.src=fmdc.imagepath+'/expand.png';
		}
	});
}

return {
	initMeta : fmdf_initComponentMeta,
	initVar : fmdf_initvar,
	onresize : fmdf_onresize,
	isEditor : function() {return fmd.isEditor;},
	loadModules : fmdf_loadModules,
	loadJsFile : loadJsFile,
	waitstart : waitstart,
	waitend : waitend,
	loadJsFile : loadJsFile,
	getSelected : fmdf_getSelected,
	onselect : fmdf_onselect,
	enableApply : fmdf_enableApply,
	loadHistory : fmdf_loadHistory,
	fmcontainer_tab_title : fmdf_fmcontainer_tab_title,
	fmcontainer_block_title : fmdf_fmcontainer_block_title,
	fmcontainer_block_headerdisplay : fmdf_fmcontainer_block_headerdisplay,
	init : fmdf_init
}

};
